python - Pandas 的前一组均值变化

标签 python pandas

我有一个如下所示的表格:

date         revenue
2021-01-01   20
2021-01-02   30
...
2021-01-31   50
2021-02-01   35
2021-02-02   67

我想计算上个月每行的最大收入。

我可以计算当月的最大收入:

df['max']=df.groupby(df['date'].dt.month)[revenue'].transform(max)

它看起来像这样:

  date         revenue  max
2021-01-01   20         50
2021-01-02   30         50
...
2021-01-31   50         50
2021-02-01   35         67
2021-02-02   67         67

但我希望它是:

  date         revenue  max
2021-01-01   20         nan
2021-01-02   30         nan
...
2021-01-31   50         nan
2021-02-01   35         50
2021-02-02   67         50

我尝试将 .shift() 放在最后,但它只会滞后/领先 max 行,但我需要按组排列它。

请帮忙

最佳答案

您可以使用 shift map 进行groupby

s = df.date.dt.strftime('%Y%m')
df['new'] = s.map(df.groupby(s).revenue.max().shift())
df
Out[62]: 
        date  revenue   new
0 2021-01-01       20   NaN
1 2021-01-02       30   NaN
2 2021-01-31       50   NaN
3 2021-02-01       35  50.0
4 2021-02-02       67  50.0

关于python - Pandas 的前一组均值变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69905805/

相关文章:

python - 是否有任何关于 python 模块 vim 的文档——用于 vim 插件开发?

python - Paraview - 使用 python 脚本以 x3d 格式导出数据

python - 如何将 SQL 数据框中列的单个 MIN 值作为标量返回?

python - 为什么我不能在 multiprocessing.Pool 中使用 operator.itemgetter?

python - Pandas 数据框。更改 float 格式。保留类型 "float"

Python 的图形工具 : Generate egonet up n-th degree

python - 如何完全重置警告

python - 屏蔽 pandas DataFrame 中最大值之前出现的所有值

python - 根据列使用函数满足的条件在 Pandas 中创建新列

python - 无法对列数据重新排序