[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()])


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM