获取时间序列熊猫每个月的最后日期

ike*_*lem 10 python pandas zipline

目前我正在使用某个函数生成DateTimeIndex zipline.utils.tradingcalendar.get_trading_days.时间序列大致是每天,但有一些差距.

我的目标是获得DateTimeIndex每月的最后日期.

.to_period('M')&.to_timestamp('M')不工作,因为它们给出了月份的最后一天,而不是每月的变量的最后一个值.

例如,如果这是我的时间序列,我想选择"2015-05-29",而月份的最后一天是"2015-05-31".

['2015-05-18','2015-05-19','2015-05-20','2015-05-21','2015-05-22','2015-05-26',' 2015-05-27','2015-05-28','2015-05-29','2015-06-01']

ike*_*lem 6

Condla的答案最接近我所需要的,除了因为我的时间指数延长了一年多,我需要按月和年分组,然后选择最大日期.下面是我最终得到的代码.

# tempTradeDays is the initial DatetimeIndex
dateRange = []  
tempYear = None  
dictYears = tempTradeDays.groupby(tempTradeDays.year)
for yr in dictYears.keys():
    tempYear = pd.DatetimeIndex(dictYears[yr]).groupby(pd.DatetimeIndex(dictYears[yr]).month)
    for m in tempYear.keys():
        dateRange.append(max(tempYear[m]))
dateRange = pd.DatetimeIndex(dateRange).order()
Run Code Online (Sandbox Code Playgroud)


小智 6

假设你的数据框看起来像这样

原始数据框

那么下面的代码将为您提供每个月的最后一天。

df_monthly = df.reset_index().groupby([df.index.year,df.index.month],as_index=False).last().set_index('index')
Run Code Online (Sandbox Code Playgroud)

转换后的数据框

这一行代码完成了它的工作:)