简体   繁体   English

如何在python panda数据框中找到所有零单元格并替换它们?

[英]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.

相关问题 使用 Python Panda 在 csv 中搜索包含低于零的数字的单元格 - 然后将其替换为左右单元格的平均值 - Search through .csv using Python Panda for cells containing numbers below zero - then replace them with the average of the cells left and right of it 如何根据条件替换 Panda 数据框列中的单元格 - How do I replace cells in a Panda dataframe column based on a condition 如何在pandas/python中查找和替换具有属性的所有单元格 - How to find and replace all cells with an attribute in pandas/python Python:熊猫 Dataframe 替换为另一个 Dataframe - Python: Panda Dataframe replace with another Dataframe 如何在列中查找名称相似的单元格并使用Python和Pandas DataFrame对其进行汇总 - How to find cells with a similar name in the column and summarize them with Python, and Pandas DataFrame 如何在Python中创建所有零数据帧 - how to create all zero dataframe in Python 如何查找 Panda Dataframe 中的错误值在哪里 - How to find where is the error value in the Panda Dataframe 如何找出全部用零填充的行或列,并在python的pandas.DataFrame中将其删除? - How to find out the rows or columns all filled with zeros and delete them in pandas.DataFrame in python? 如何在python中查找和替换数据框中的单个值 - How to find and replace a single value in a dataframe in python Panda dataframe 查找其他列的所有可能值都存在的行 - Panda dataframe find row that are present for all possible value of other columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM