我正在使用python 3.5并导入了numpy和pandas库.我创建了一个名为df的DataFrame,其索引从零开始,有两列;变化百分比(PofChg)和向上,向下或平坦(U_D_F).
对于U_D_F列,我想根据PofChg列填充“Up”,“Down”,“Flat”字样. Up表示大于零,Down表示小于零,Flat表示等于零.
除了两件事之外,np.where函数似乎运行良好,
(1)当PofChg列中的数字为“Zero”时,为什么在U_D_F列中显示“Down”
(2)如何使np.where函数接受更多参数,即不是说 – 如果df.PofChg是> 0,如果true显示“Up”或者如果false显示“Down”,我想将其更改为 – 如果df.PofChg是> 0,如果true显示“Up”或假显示“Down”,但如果它等于零则显示“Flat”
这是我打印df时的当前输出
PofChg U_D_F
0 -1 Down
1 0 Down
2 1 Up
3 -2 Down
4 0 Down
5 5 Up
6 3 Up
7 -6 Down
Press any key to continue . . .
这是我的代码
import pandas as pd
import numpy as np
df = pd.DataFrame({'PofChg':[-1,0,1,-2,0,5,3,-6]})
df['U_D_F'] = np.where(df.PofChg > 0 , 'Up','Down');df
print(df)
解决方法:
Why is it displaying “Down” in the U_D_F column when the number in the PofChg column is “Zero”
那是因为你对np.where的条件是> 0,所以,如果它为0,则条件失败,并选择替代方案.
I want to change it to – if df.PofChg is > 0, if true display “Up” or if false display “Down”, but if it is equal to zero then display “Flat”
np.where(df.PofChg > 0 , 'Up', np.where(df.PofChg == 0, 'Flat', 'Down'))
如果df.PofChg> 0,它选择’Up’;否则,如果df.PofChg == 0,则选择“Flat”,否则选择“Down”.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。