【问题标题】:Replace value in column based on a condition [duplicate]根据条件替换列中的值[重复]
【发布时间】:2021-05-09 10:21:14
【问题描述】:

我有一个 DF

***********************
Product       Rate      Imputed_rate      min_rate

1              0        10                5
2              0        4                 7
3              0        34                2
4              0        3                 8
***************************

我想在 Rate=0 时替换该行;仅当 'Imputed_rate' 时才使用 'min_rate'


最好的方法是什么?


期望的输出:


Product       Rate      Imputed_rate      min_rate

1             0         10                5
2             7         4                 7
3             0         34                2
4             8         3                 8
***************************

【问题讨论】:

  • 显示你想要的输出。

标签: python pandas dataframe


【解决方案1】:

np.where是你的朋友https://numpy.org/doc/stable/reference/generated/numpy.where.html

df['Rate'] = np.where(((df['Rate'] == 0) & (df['Imputed_rate'] < df['min_rate'])), df['min_rate'],df['Rate'])

对于 pandas 中的行,它基本上是一个 if then else。

【讨论】:

    【解决方案2】:

    这是另一个不使用 numpy 的答案:

    df['Rate'] = df.apply(lambda row: row['min_rate'] if row['Imputed_rate'] < row['min_rate'] else row['Rate'],axis = 1)
    
    #Output:
       Product  Rate  Imputed_rate  min_rate
    0        1     0            10         5
    1        2     7             4         7
    2        3     0            34         2
    3        4     8             3         8
    

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 2019-01-02
      • 2016-08-29
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多