根据条件替换列中的值

时间:2021-02-05 03:20:26

标签: python pandas dataframe

我有一个 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
***************************

2 个答案:

答案 0 :(得分: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'])

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

答案 1 :(得分:0)

这是不使用 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
相关问题