pandas 计算两个零之间不为零的值的数量 [英] pandas count the number of value different from zero between two zeros

查看:55
本文介绍了 pandas 计算两个零之间不为零的值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框

0 0 0
1 0 0 
1 1 0
1 1 1
1 1 1
0 0 0
0 1 0
0 1 0
0 0 0 

你如何获得看起来像这样的数据框

how do you get a dataframe which looks like this

0 0 0
4 0 0 
4 3 0
4 3 2
4 3 2
0 0 0
0 2 0
0 2 0
0 0 0

感谢您的帮助.

推荐答案

您可能需要在这里使用 for 循环,使用 tranform,并使用 cumsum 创建密钥并分配位置回到你原来的 df

You may need using for loop here , with tranform, and using cumsum create the key and assign the position back to your original df

for x in df.columns:
    df.loc[df[x]!=0,x]=df[x].groupby(df[x].eq(0).cumsum()[df[x]!=0]).transform('count')

df
Out[229]: 
     1    2    3
0  0.0  0.0  0.0
1  4.0  0.0  0.0
2  4.0  3.0  0.0
3  4.0  3.0  2.0
4  4.0  3.0  2.0
5  0.0  0.0  0.0
6  0.0  2.0  0.0
7  0.0  2.0  0.0
8  0.0  0.0  0.0

或者没有 for 循环

Or without for loop

s=df.stack().sort_index(level=1)
s2=s.groupby([s.index.get_level_values(1),s.eq(0).cumsum()]).transform('count').sub(1).unstack()
df=df.mask(df!=0).combine_first(s2)
df
Out[255]: 
     1    2    3
0  0.0  0.0  0.0
1  4.0  0.0  0.0
2  4.0  3.0  0.0
3  4.0  3.0  2.0
4  4.0  3.0  2.0
5  0.0  0.0  0.0
6  0.0  2.0  0.0
7  0.0  2.0  0.0
8  0.0  0.0  0.0

这篇关于 pandas 计算两个零之间不为零的值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆