Pandas DataFrame 滚动计数

Pandas DataFrame rolling count

我有以下 pandas 数据框(仅作为示例):

import pandas as pd
df = pd.DataFrame(pd.Series(['a','a','a','b','b','c','c','c','c','b','c','a']), columns = ['Data'])


   Data
0     a
1     a
2     a
3     b
4     b
5     c
6     c
7     c
8     c
9     b
10    c
11    a

目标是获取另一列 Stats,计算 Data 列的元素,如下所示:

   Data Stats
0     a      
1     a      
2     a    a3
3     b      
4     b    b2
5     c      
6     c      
7     c      
8     c    c4
9     b    b1
10    c    c1
11    a    a1

其中,例如,a3 表示 "three consecutive a elements",c4 表示 "four consecutive c elements" 等等。 .

提前感谢您的帮助

这是使用 groupby 的一种方法:

counts = df.groupby((df['Data'] != df['Data'].shift()).cumsum()).cumcount() + 1

df['Stats'] = np.where(df['Data'] != df['Data'].shift(-1),
                       df['Data'] + counts.astype(str), '')

print(df)

   Data Stats
0     a      
1     a      
2     a    a3
3     b      
4     b    b2
5     c      
6     c      
7     c      
8     c    c4
9     b    b1
10    c    c1
11    a    a1

为列 Data 的连续值创建助手 Series s,按 GroupBy.transform 计算每组的计数,最后将重复的值替换为空 string小号:

s = df['Data'].ne(df['Data'].shift()).cumsum()
a = df.groupby(s)['Data'].transform('size')

df['Stats'] = np.where(~s.duplicated(keep='last'), df['Data'] + a.astype(str), '')
print (df)
   Data Stats
0     a      
1     a      
2     a    a3
3     b      
4     b    b2
5     c      
6     c      
7     c      
8     c    c4
9     b    b1
10    c    c1
11    a    a1

详情:

print (s)
0     1
1     1
2     1
3     2
4     2
5     3
6     3
7     3
8     3
9     4
10    5
11    6
Name: Data, dtype: int32

print (a)
0     3
1     3
2     3
3     2
4     2
5     4
6     4
7     4
8     4
9     1
10    1
11    1
Name: Data, dtype: int64

不删除重复的解决方案更简单:

df['Stats'] = df['Data'] + a.astype(str)
print (df)

   Data Stats
0     a    a3
1     a    a3
2     a    a3
3     b    b2
4     b    b2
5     c    c4
6     c    c4
7     c    c4
8     c    c4
9     b    b1
10    c    c1
11    a    a1