简体   繁体   中英

How to find all the zero cells in a python panda dataframe and replace them?

My data is like this:

df = pd.DataFrame({'a': [5,0,0, 6, 0, 0, 0 , 12]})

I want to count the zeros above the 6 and replace them with (6/count+1)=(6/3)=2 (I will also replace the original 6) I also want to do a similar thing with the zeros above the 12. So, (12/count)=(12/3)=4 So the final result will be:

[5,2,2, 2, 3, 3, 3 , 3]

I am not sure how to start. Are there any functions that do this? Thanks.

Use GroupBy.transform with mean and custom groups created with test not equal 0 , swap order, cumulative sum and swap order to original:

g = df['a'].ne(0).iloc[::-1].cumsum().iloc[::-1]
df['b'] = df.groupby(g)['a'].transform('mean')
print (df)
    a  b
0   5  5
1   0  2
2   0  2
3   6  2
4   0  3
5   0  3
6   0  3
7  12  3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM