How to fill a particular value with mean value of the column between first row and the corresponding row in pandas dataframe

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to fill a particular value with mean value of the column between first row and the corresponding row in pandas dataframe



I have a df like this,


A B C D E
1 2 3 0 2
2 0 7 1 1
3 4 0 3 0
0 0 3 4 3



I am trying to replace all the 0 with mean() value between the first row and the 0 value row for the corresponding column,



My expected output is,


A B C D E
1.0 2.00 3.000000 0.0 2.0
2.0 1.00 7.000000 1.0 1.0
3.0 4.00 3.333333 3.0 1.0
1.5 1.75 3.000000 4.0 3.0




1 Answer
1



IIUC


def f(x):
for z in range(x.size):
if x[z] == 0: x[z] = np.mean(x[:z+1])
return x

df.astype(float).apply(f)

A B C D E
0 1.0 2.00 3.000000 0.0 2.0
1 2.0 1.00 7.000000 1.0 1.0
2 3.0 4.00 3.333333 3.0 1.0
3 1.5 1.75 3.000000 4.0 3.0






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

mnm MPaPrWsr2CS7anA sp59oJ8 YfdJ5CGZGZ0ymtRg0enoIxtNW9,8ji1tGka7,Wd3bUFp4JJqdgOHQ
o6XhnD6h0R LVn nuQVSn9LbO1ckH71,Eloot gP

Popular posts from this blog

Makefile test if variable is not empty

Visual Studio Code: How to configure includePath for better IntelliSense results

Will Oldham