python - 有没有办法在数据框中找到每月最后一天的值

标签 python pandas dataframe group-by

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

原始df:

<表类=“s-表”> <标题> 项目 日期 数量 <正文> 苹果 21/09/23 2143 bat 2021年9月21日 2444 可乐 15/09/21 1512 苹果 21/10/21 2906 bat 21/4/10 2730 可乐 16/10/21 2449 可乐 2021年12月31日 0 苹果 2021年12月27日 1086 bat 2021年12月25日 1186 苹果 2021年12月26日 1377

目标 df:

<表类=“s-表”> <标题> 项目 日期 数量 <正文> 可乐 2021年12月31日 0 苹果 2021年12月27日 1086 bat 2021年12月25日 1186

有什么办法可以获取吗?

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

最佳答案

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

关于python - 有没有办法在数据框中找到每月最后一天的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70517474/

相关文章:

Python 和 Selenium - 离开页面时禁用警报

Python 一行打印当前目录中的每个文件

python - 按 2 个字段排序?是否有任何 hack 或 index.yaml?还是geoPT?

python - 在 pandas 中应用 1 到组转换 - python

按组用第一个观察值替换所有值

r - 如何按总和标准化数据帧值(获取百分比)

pandas - 由于 "reshaping"问题,无法在 scikit-Learn 中进行线性回归

python-2.7 - 如何使用Pandas read_html和requests库读取表格?

python - 如何将 pandas DataFrame 的第一列作为一个系列?

Python/Sklearn - 值错误 : could not convert string to float