【问题标题】:If/else with Python Pandas Dataframe使用 Python Pandas 数据框的 if/else
【发布时间】: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


【解决方案1】:

使用您尝试的方法:

In [1100]: col         = 'bonus' 
      ...: conditions  = [ df['bonus'] < 0.8 , df['bonus'] > 1.2] 
      ...: choices     = [0.8, 1.2]                                                                                                                                                                         

In [1102]: df['bonus_capped'] = np.select(conditions, choices, default=df['bonus'])                                                                                                                         

In [1103]: df                                                                                                                                                                                               
Out[1103]: 
   id  bonus  bonus_capped
0   1   1.50          1.20
1   2   1.12          1.12
2   3   1.09          1.09
3   4   0.9           0.9
4   5   0.74          0.80
5   6   0.83          0.83

【讨论】:

  • 如果对您有帮助,请点赞并接受答案。
【解决方案2】:

这很容易使用numpy.clip:

import numpy as np

df['bonus_capped'] = np.clip(df['bonus'], 0.8, 1.2)

其中 0.8 和 1.2 分别是您的下限和上限。

【讨论】:

    【解决方案3】:

    pandas

    upper_limit = 1.2
    lower_limit = 0.8
    df.bonus.clip(lower_limit,upper_limit)
    0    1.20
    1    1.12
    2    1.09
    3    0.90
    4    0.80
    5    0.83
    Name: bonus, dtype: float64
    #df.bonus=df.bonus.clip(lower_limit,upper_limit)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-22
      • 2021-01-28
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多