Home > Software design >  Replacing values on cell by multiplier by other row in Pandas
Replacing values on cell by multiplier by other row in Pandas

Time:04-29

I have the following dataframe:

enter image description here

I want to verify if the value of a cell is 0 for any date. If it is, I want to replace the value of the cell by multiplying the value on the previous cell by the proper multiplier.

For example, Day 14 = 0, I want to multiply Day 7 by Mul 14 and store the new value in Day 14. And so on with the whole dataframe.

I have tried this code but it is not working:

if df['day 30'] == 0.00:
  df['day 30'] = df['day 14']*df['Mul 30']

And this is my expected output:

enter image description here

Thanks!

CodePudding user response:

Here is a solution with small example:

import pandas as pd
import numpy as np
df=pd.DataFrame([[0.8,0.9,0.7,2,6],[0.6,0,0,2,3],[0.2,0,0,4,2]],columns=["Day 7","Day 14","Day 30","Mul 14","Mul 30"])
print(df)
df["Day 14"]=np.where(df["Day 14"]==0,df["Day 7"]*df["Mul 14"],df["Day 14"])
df["Day 30"]=np.where(df["Day 30"]==0,df["Day 14"]*df["Mul 30"],df["Day 30"])
print(df)

If you want ypu can iterate over [7,14,10,90] instead of writing individual lines.

Result of above code:

   Day 7  Day 14  Day 30  Mul 14  Mul 30
0    0.8     0.9     0.7       2       6
1    0.6     0.0     0.0       2       3
2    0.2     0.0     0.0       4       2
   Day 7  Day 14  Day 30  Mul 14  Mul 30
0    0.8     0.9     0.7       2       6
1    0.6     1.2     3.6       2       3
2    0.2     0.8     1.6       4       2
  • Related