我正在使用 python 3.5 并导入了 numpy 和 pandas 库。我创建了一个名为 df 的 DataFrame,它有一个从零开始的索引和两列;变化百分比 (PofChg) 和向上、向下或持平 (U_D_F)。

对于 U_D_F 列,我想根据 PofChg 列用“向上”、“向下”、“平坦”等词填充它。 Up 表示大于零,Down 表示小于零,Flat 表示等于零。

np.where 函数似乎运行良好,除了两件事,
(1)为什么PofChg列的数字为“0”时U_D_F列显示“Down”
(2) 如何让 np.where 函数接受更多参数,即不是说 - 如果 df.PofChg > 0 ,如果真显示“向上”或假显示“向下”,我想将其更改为 -如果 df.PofChg > 0,如果真显示“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)

最佳答案



那是因为您对 np.where 的条件 > 0,因此,如果它是 0,则条件失败,并选择替代方案。


np.where(df.PofChg > 0 , 'Up', np.where(df.PofChg == 0, 'Flat', 'Down'))

如果 df.PofChg > 0 ,则选择 'Up' ;否则,如果 df.PofChg == 0 ,则选择 'Flat' ,否则选择 'Down'

关于python - 我如何让 np.where 接受更多参数,以便过滤 >、< 和 =;不仅仅是 > 和 <?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39548753/

10-10 19:10