保持日期在pandas groupby滚动聚合中。

huangapple go评论87阅读模式
英文:

Keep date in pandas groupby rolling aggregation

问题

I'm running the code below for computing rolling statistics over date on a dataset.

  1. import pandas as pd
  2. df = pd.DataFrame({'id': [1, 1, 1, 2, 2, 2],
  3. 'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-01', '2023-01-02', '2023-01-03'],
  4. 'value': [5, 4, 7, 2, 7, 1]})
  5. df['date'] = pd.to_datetime(df['date'])
  6. df.groupby('id')['value'].rolling(2).agg({'sum': 'sum', 'mean': 'mean'})

The code does not keep date in the result. Ideally I would like to keep the date for each statistics over time, but I only get an index number.

英文:

I'm running the code below for computing rolling statistics over date on a dataset.

  1. import pandas as pd
  2. df = pd.DataFrame({'id': [1, 1, 1, 2, 2, 2],
  3. 'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-01', '2023-01-02', '2023-01-03'],
  4. 'value': [5, 4, 7, 2, 7, 1]})
  5. df['date'] = pd.to_datetime(df['date'])
  6. df.groupby('id')['value'].rolling(2).agg({'sum': 'sum', 'mean': 'mean'})

The code does not keep date in the result. Ideally I would like to keep the date for each statistics over time, but I only get an index number.

答案1

得分: 1

date设置为索引以在聚合过程中保留它:

  1. out = (df.set_index('date').groupby('id')['value']
  2. .rolling(2).agg(['sum', 'mean']).reset_index())
  3. print(out)

  1. id date sum mean
  2. 0 1 2023-01-01 NaN NaN
  3. 1 1 2023-01-02 9.0 4.5
  4. 2 1 2023-01-03 11.0 5.5
  5. 3 2 2023-01-01 NaN NaN
  6. 4 2 2023-01-02 9.0 4.5
  7. 5 2 2023-01-03 8.0 4.0
英文:

Set date as index to preserve it during aggregation:

  1. out = (df.set_index('date').groupby('id')['value']
  2. .rolling(2).agg(['sum', 'mean']).reset_index())
  3. print(out)

  1. id date sum mean
  2. 0 1 2023-01-01 NaN NaN
  3. 1 1 2023-01-02 9.0 4.5
  4. 2 1 2023-01-03 11.0 5.5
  5. 3 2 2023-01-01 NaN NaN
  6. 4 2 2023-01-02 9.0 4.5
  7. 5 2 2023-01-03 8.0 4.0

huangapple
  • 本文由 发表于 2023年5月6日 21:58:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定