pandas 与Groupby一起滚动最大值

发布时间:2022-07-21 / 作者:清心寡欲
本文介绍了 pandas 与Groupby一起滚动最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让 pandas 的rolling函数执行我想要的操作。我想让每个FROW计算到目前为止组内的最大值。下面是一个例子:

df = pd.DataFrame([[1,3], [1,6], [1,3], [2,2], [2,1]], columns=['id', 'value'])

看起来像

   id  value
0   1      3
1   1      6
2   1      3
3   2      2
4   2      1

现在我希望获得以下DataFrame:

   id  value
0   1      3
1   1      6
2   1      6
3   2      2
4   2      2

问题是当我这样做时

df.groupby('id')['value'].rolling(1).max()

我得到的是相同的DataFrame。当我这样做的时候

df.groupby('id')['value'].rolling(3).max()

我得到了Nans的DataFrame。谁能解释一下如何正确使用rolling或其他一些Pandas函数来获取我想要的DataFrame?

推荐答案

看起来您需要cummax()而不是.rolling(N).max()

In [29]: df['new'] = df.groupby('id').value.cummax()

In [30]: df
Out[30]:
   id  value  new
0   1      3    3
1   1      6    6
2   1      3    6
3   2      2    2
4   2      1    2

计时(使用全新的 pandas 0.20.1版):

In [3]: df = pd.concat([df] * 10**4, ignore_index=True)

In [4]: df.shape
Out[4]: (50000, 2)

In [5]: %timeit df.groupby('id').value.apply(lambda x: x.cummax())
100 loops, best of 3: 15.8 ms per loop

In [6]: %timeit df.groupby('id').value.cummax()
100 loops, best of 3: 4.09 ms per loop

注意:from Pandas 0.20.0 what's new

  • groupby().cummin()groupby().cummax()(GH15048,GH15109,GH15561,GH15635)的性能提高)

这篇关于 pandas 与Groupby一起滚动最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]pandas rolling max with groupby


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。