[英]Setting the datetime in a multiindex to last day of the month
I have a Multiindex Dataframe and would like to change the date level, so that the date of the last value I have for each month is changed to the last day of the month.我有一个 Multiindex Dataframe 并且想更改日期级别,以便我每个月的最后一个值的日期更改为该月的最后一天。 Any help is appreciated.任何帮助表示赞赏。
The DataFrame (rolling_cov) 123610 rows × 10 columns: DataFrame (rolling_cov) 123610行×10列:
Date NoDur Durbl Manuf
2018-12-27 NoDur 0.000109 0.000112 0.000118
Durbl 0.000112 0.000339 0.000238
Manuf 0.000118 0.000238 0.000246
2018-12-28 NoDur 0.000109 0.000113 0.000117
Durbl 0.000113 0.000339 0.000239
Manuf 0.000117 0.000239 0.000242
2018-12-31 NoDur 0.000109 0.000113 0.000118
Durbl 0.000113 0.000339 0.000239
Manuf 0.000118 0.000239 0.000245
The Code I tried:我试过的代码:
rolling_cov.index=
rolling_cov.index.set_levels([rolling_cov.index.levels[0].
apply(pd.to_datetime(df['Date'] , format="%Y%m") + MonthEnd(1))])
The error I received:我收到的错误:
'DatetimeIndex' object has no attribute 'apply'
It may be easier to convert it to a Series first, change the values, and then replace the original index with the new one.首先将其转换为系列,更改值,然后用新索引替换原始索引可能更容易。
idx = df.index.levels[0]
ser = pd.Series(idx)
last_of_mon = ser.groupby(ser.dt.year * 100 + ser.dt.month).last()
ser = ser.apply(
lambda x: x + pd.offsets.MonthBegin(1) - pd.offsets.Day(1)
if x in last_of_mon.values
else x
)
df.index.set_levels(ser, 0, inplace=True)
Notice that + pd.offsets.MonthBegin(1) - pd.offsets.Day(1)
is used to change to the last of the month.请注意, + pd.offsets.MonthBegin(1) - pd.offsets.Day(1)
用于更改为月末。 If you use + pd.offsets.MonthEnd(1)
on a date that is already the last of the month, it changes it to the last of the next month.如果您在已经是本月最后一天的日期使用+ pd.offsets.MonthEnd(1)
,则会将其更改为下个月的最后一天。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.