【问题标题】:Is there a way to find the value for the last day of each month in a dataframe有没有办法在数据框中找到每个月最后一天的值
【发布时间】:2021-12-29 09:26:06
【问题描述】:

我有一个数据框,可以为我提供各种文章的每日数量水平。我想获得一个数据框,它可以为我提供每篇文章每个月最后一天的数量水平。

原始 df:

item Date Quantity
apple 23/09/21 2143
bat 21/09/2021 2444
cola 15/09/21 1512
apple 21/10/21 2906
bat 4/10/21 2730
cola 16/10/21 2449
cola 31/12/2021 0
apple 27/12/2021 1086
bat 25/12/2021 1186
apple 26/12/2021 1377

目标df:

item Date Quantity
cola 31/12/2021 0
apple 27/12/2021 1086
bat 25/12/2021 1186

有没有办法获得?

我尝试使用 tail() 按项目和日期分组,但没有成功。

【问题讨论】:

  • “我尝试使用 tail() 按项目和日期分组,但没有成功。”显示您尝试过的内容。 How to Askminimal reproducible example
  • 在原始数据框中,您的日期是 9 月和 10 月,而在目标 df 中,您的日期都在 12 月。您的问题是“每个月最后一天的数量水平”文章”,请澄清这一点

标签: python pandas dataframe group-by


【解决方案1】:

IIUC 需要 GrouperGroupBy.tail 每年的最后一个值:

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

df = df.groupby(['item', pd.Grouper(freq='Y', key='Date')]).tail(1)
print (df)
    item       Date  Quantity
6   cola 2021-12-31         0
8    bat 2021-12-25      1186
9  apple 2021-12-26      1377

因为每个月的输出不同:

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

df = df.groupby(['item', pd.Grouper(freq='m', key='Date')]).tail(1)
print (df)
    item       Date  Quantity
0  apple 2021-09-23      2143
1    bat 2021-09-21      2444
2   cola 2021-09-15      1512
3  apple 2021-10-21      2906
4    bat 2021-10-04      2730
5   cola 2021-10-16      2449
6   cola 2021-12-31         0
8    bat 2021-12-25      1186
9  apple 2021-12-26      1377

【讨论】:

  • 谢谢@jezrael。我不知道 pd.grouper 它工作得很好,我学到了一些新东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
相关资源
最近更新 更多