簡體   English   中英

在 pandas DataFrame 中對相同的連續值進行分組

[英]Group identical consecutive values in pandas DataFrame

我有以下 pandas dataframe:

   a
0  0
1  0
2  1
3  2
4  2
5  2
6  3
7  2
8  2
9  1

我想將這些值存儲在另一個 dataframe 中,例如每組連續的相同值都會形成一個像這樣的標記組:

   A  B
0  0  2
1  1  1
2  2  3
3  3  1
4  2  2
5  1  1

A 列表示組的值,B 表示出現次數。

這是我到目前為止所做的:

df = pd.DataFrame({'a':[0,0,1,2,2,2,3,2,2,1]})
df2 = pd.DataFrame()
for i,g in df.groupby([(df.a != df.a.shift()).cumsum()]):
    vc = g.a.value_counts()
    df2 = df2.append({'A':vc.index[0], 'B': vc.iloc[0]}, ignore_index=True).astype(int)

它有效,但有點混亂。

您是否想到了一種最短/更好的方法?

我會嘗試:

df['blocks'] = df['a'].ne(df['a'].shift()).cumsum()
(df.groupby(['a','blocks'],
           as_index=False,
           sort=False)
   .count()
   .drop('blocks', axis=1)
)

Output:

   a  B
0  0  2
1  1  1
2  2  3
3  3  1
4  2  2
5  1  1

在 Pandas >0.25.0 中使用 GrouBy.agg GrouBy.agg

new_df= ( df.groupby(df['a'].ne(df['a'].shift()).cumsum(),as_index=False)
            .agg(A=('a','first'),B=('a','count')) )

print(new_df)

   A  B
0  0  2
1  1  1
2  2  3
3  3  1
4  2  2
5  1  1

pandas <0.25.0

new_df= ( df.groupby(df['a'].ne(df['a'].shift()).cumsum(),as_index=False)
            .a
            .agg({'A':'first','B':'count'}) )

暫無
暫無

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

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