[Tips] pandas获取每月最后一天

以pandas时间格式存储日期时,可以通过如下方式获取一个datetimeIndex内每个月的最后一天

# daily_price是一个以datetimeIndex为index的DataFrame或Series
tmp_dict = daily_price.index.groupby(daily_price.index.month)
[max(tmp_dict[month]) for month in tmp_dict]

如果是以datatimeIndex作为index,想在数据上操作(比如取一批数据在每个月末的平均值),过滤出每个月最后一天的相关数据

from pandas.tseries.offsets import MonthEnd
offset = MonthEnd()
daily_price.groupby(offset.rollforward).apply(lambda t: t[t.index == t.index.max()])
posted @ 2021-05-25 15:25  虚无真仙  阅读(2497)  评论(0编辑  收藏  举报