【发布时间】:2020-07-30 02:54:08
【问题描述】:
为这个菜鸟问题道歉,但我在 python 条件下遇到了困难。
有以下数据框:
id bonus
1 1.5
2 1.12
3 1.09
4 0.9
5 0.74
6 0.83
我有上限和下限变量:
upper_limit = 1.2
lower limit = 0.8
试图写一个条件: 1) 检查奖金是否高于或低于阈值 2) 创建一个新列,以确保该值不会高于或低于阈值。如果奖励值在范围内,则不会改变。
应该是这样的:
id bonus bonus_capped
1 1.5 1.2
2 1.12 1.12
3 1.09 1.09
4 0.9 0.9
5 0.74 0.8
6 0.83 0.83
我的代码是:
conditions = [df["bonus"] > upper_limit, df["bonus"] < lower_limit]
choices = [upper_limit, lower_limit]
df["bonus_capped"] = np.select(conditions, choices)
print(df)
但我得到的输出只是解决一个条件,其余的返回零。我错过了什么?
id bonus bonus_capped
1 1.5 0
2 1.12 0
3 1.09 0
4 0.9 0
5 0.74 0.8
6 0.83 0
【问题讨论】:
-
你的代码对我有用 - 另外它返回 0 因为这是默认值 - 试试
np.select(conditions, choices,default=df['bonus'])
标签: python pandas numpy dataframe conditional-statements