【问题标题】:Converting daily data to monthly and get months last value in pandas将每日数据转换为每月数据并在熊猫中获得几个月的最后一个值
【发布时间】:2020-12-23 10:47:20
【问题描述】:

我的数据由像这样属于特定月份和年份的每日数据组成

我想将所有每日数据转换为每月数据,并且我想获取该月的最后一个值作为该月数据的返回值 例如:

AccoutId,   Date,    Return

  1       2016-01   -4.1999  (Because this return value is last value of january 1/29/16)

  1       2016-02    0.19    (Same here last value of february 2/29/16)
and so on

我看过一些关于将每日数据转换为每月数据的主题,但问题是在将每日数据转换为每月数据后,他们将当月的 mean() 或 sum() 作为返回值。反之,我想要那个月的最后一个返回值作为返回值。

【问题讨论】:

  • 这是一个标准的 pandas 问题,实际上与 machine-learning 无关 - 请不要向无关标签发送垃圾邮件(已删除)。

标签: pandas dataframe


【解决方案1】:

您可以按AccountId 和年月分组。先转换为日期时间,然后格式化为年月,如下所示:df['Date'].dt.strftime('%Y-%m')。然后就用last():

df['Date'] = pd.to_datetime(df['Date'])
df = df.groupby(['AccountId', df['Date'].dt.strftime('%Y-%m')])['Return'].last().reset_index()
df

样本数据:

In[1]:
   AccountId     Date  Return
0          1   1/7/16      15
1          1  1/29/16      10
2          1   2/1/16      25
3          1  2/15/16      20
4          1  2/28/16      30

df['Date'] = pd.to_datetime(df['Date'])
df = df.groupby(['AccountId', df['Date'].dt.strftime('%Y-%m')])['Return'].last().reset_index()
df

Out[1]: 
   AccountId     Date  Return
0          1  2016-01      10
1          1  2016-02      30

【讨论】:

  • @RutkayKarabulak 在我对数据框名称的回答中更改df。您不应该收到该错误。您的数据框的名称是什么?
  • 哦,好的,我现在已经完成了,我只是打了一些错字,就是这样。非常感谢大卫!
猜你喜欢
  • 2015-03-23
  • 2022-06-30
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
相关资源
最近更新 更多