连续发生2次以上事件的计数

2024-10-06 12:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我是初学者,我真的需要以下方面的帮助:

我需要做与下面类似的事情,但是在二维数据帧Identifying consecutive occurrences of a value

我需要使用这个答案,但对于二维数据帧。我需要沿着列维度计算至少两个连续的列。以下是一个示例数据帧: 我的_df=

 0 1 2
0 1 0 1
1 0 1 0
2 1 1 1
3 0 0 1
4 0 1 0
5 1 1 0
6 1 1 1
7 1 0 1

我想要的输出是:

  0 1 2
0 3 5 4

我需要一个名为“out_1_df”的新输出来代替列“continued”

df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count

这样以后我就可以做了

    threshold = 2; 
    out_2_df= (out_1_df > threshold).astype(int)

我尝试了以下方法:

out_1_df= my_df.groupby(( my_df != my_df.shift(axis=0)).cumsum(axis=0)) 
out_2_df =`(out_1_df > threshold).astype(int)`  

我如何修改这个


Tags: 数据dfthresholdshiftmycountout事情
1条回答
网友
1楼 · 发布于 2024-10-06 12:09:50

尝试:

import pandas as pd

df=pd.DataFrame({0:[1,0,1,0,0,1,1,1], 1:[0,1,1,0,1,1,1,0], 2: [1,0,1,1,0,0,1,1]})

out_2_df=((df.diff(axis=0).eq(0)|df.diff(periods=-1,axis=0).eq(0))&df.eq(1)).sum(axis=0)

>>> out_2_df

[3 5 4]

相关问题 更多 >