1

I have a DF

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

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

I want to replace the row when Rate=0 ; with the 'min_rate' only if 'Imputed_rate'<min_rate


What is the best way to do this?


Desired Output:


Product       Rate      Imputed_rate      min_rate

1             0         10                5
2             7         4                 7
3             0         34                2
4             8         3                 8
***************************
Paul Brennan
  • 2,638
  • 4
  • 19
  • 26
anu
  • 17
  • 7

2 Answers2

1

np.where is your friend 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'])

it is basically an if then else for rows in pandas.

Paul Brennan
  • 2,638
  • 4
  • 19
  • 26
0

Here is another answer without using 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
pakpe
  • 5,391
  • 2
  • 8
  • 23