簡體   English   中英

計算連續超過 2 次出現的次數

[英]Counting number of consecutive more than 2 occurences

我是初學者,我真的需要以下幫助:

我需要做類似於以下但在二維 dataframe 識別值的連續出現

我需要使用這個答案,但對於二維 dataframe。 我需要沿列維度計算至少 2 個連續的。 這是一個示例 dataframe:my_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

我正在尋找的 output 是:

  0 1 2
0 3 5 4

我需要一個名為“out_1_df”的新 output 而不是“連續”列

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)`  

我該如何修改這個?

嘗試:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM