[英]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:我想计算 6 以上的零并用
(6/count+1)=(6/3)=2
替换它们(我也会替换原来的 6) 我也想用上面的零做类似的事情12. 所以, (12/count)=(12/3)=4
所以最终的结果是:
[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:将
GroupBy.transform
与使用 test 不等于0
创建的mean
和自定义组一起使用,交换顺序,累积总和和交换顺序到原始:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.