python - 如何让 np.where 接受更多参数,以便它过滤 >、< 和 =;不仅仅是 > 和 <?

标签 python pandas numpy dataframe where-clause

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

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

除了两件事,np.where 函数似乎运行良好, (1) 为什么PofChg 列为“0”时U_D_F 列显示“Down” (2) 我如何让 np.where 函数接受更多参数,即不是说 - 如果 df.PofChg 是 > 0 ,如果 true 显示“Up”或者如果 false 显示“Down”,我想将它更改为 -如果 df.PofChg > 0,如果为真显示“向上”,如果为假则显示“向下”,但如果它等于零则显示“平坦”

这是我打印 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'

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

相关文章:

python - 根据每个单独数据帧的行索引(编号)连接/加入/合并多个数据帧

python - 斐波那契数列从a点到b点?

python - 使用 pandas dataframe 绘制误差线 matplotlib

python - 向量化 Numpy 中的操作

python - django.db.utils.OperationalError : my_table has no column id error?

python - Pandas 从距离矩阵中按 ID 提取列和行

python - swaplevel() 和 reorder_levels() 有什么区别?

python - 比较 Pandas 数据框中的两列

python - 如何让 VSCode 的自动完成功能和 PyCharm 一样强大?

Python 调色板相机框架非常慢