Pandas 滚动 value_counts()

Pandas Rolling value_counts()

我正在 pandas 中寻找一种在滚动时间 window 中 return 特定 value_counts() 的方法。我发现了下面的问题(),但这不是我想要的。

如果我有一个如下所示的 DataFrame:

     symbol
0     apple
1     apple
2     apple
3     apple
4  cucumber
5  cucumber
6  cucumber

我想要这样的输出:

     symbol  counts
0     apple       1
1     apple       2
2     apple       3
3     apple       4
4  cucumber       1
5  cucumber       2
6  cucumber       3

到目前为止,我使用的是 for 循环,它可以工作,但对于更大的数据帧来说非常耗时:

for index in df.index:
    symbol = df.at[index,'symbol']
    df.at[index,'counts'] = df['symbol'].value_counts()[symbol]

有人有更好更快的解决方案吗?

您可以groupby“符号”并使用cumcount来获取编号(必须加1,因为cumcount从0开始):

df['counts'] = df.groupby('symbol').cumcount() + 1

输出:

     symbol  counts
0     apple       1
1     apple       2
2     apple       3
3     apple       4
4  cucumber       1
5  cucumber       2
6  cucumber       3