gpt4 book ai didi

python - Pandas 滚动最大与 groupby

转载 作者:太空狗 更新时间:2023-10-30 00:43:02 24 4
gpt4 key购买 nike

我在让 Pandas 的 rolling 函数执行我希望的操作时遇到问题。我想让每一行计算该组中到目前为止的最大值。这是一个例子:

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

关于python - Pandas 滚动最大与 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43830545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com