python - 将多索引中的日期时间设置为该月的最后一天
问题描述
我有一个多索引数据框并想更改日期级别,以便我每个月的最后一个值的日期更改为该月的最后一天。任何帮助表示赞赏。
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
我试过的代码:
rolling_cov.index=
rolling_cov.index.set_levels([rolling_cov.index.levels[0].
apply(pd.to_datetime(df['Date'] , format="%Y%m") + MonthEnd(1))])
我收到的错误:
'DatetimeIndex' object has no attribute 'apply'
解决方案
首先将其转换为系列,更改值,然后用新索引替换原始索引可能更容易。
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)
请注意,+ pd.offsets.MonthBegin(1) - pd.offsets.Day(1)
用于更改为该月的最后一天。如果您+ pd.offsets.MonthEnd(1)
在已经是本月最后一天的日期使用,它会将其更改为下个月的最后一天。
推荐阅读
- python - 如何在目录中创建json文件?
- javascript - 使用 json 文件的路径时,Jquery.i18n 不起作用
- javascript - 每次在 Photoshop 中应用特定操作后都会提示“已完成”
- google-cloud-platform - GCP VM 上的 Fluentd 代理设置未将日志推送到日志资源管理器
- sql - 没有为 C1 的第 1 列指定任何列
- excel - 将数据和带有宏的按钮复制到另一个工作簿
- javascript - Lambda 不等待 Async/Await
- reactjs - 使用 axios react 将 json 数据发布到 API
- javascript - 我在使用 React 路由器时遇到问题,因为我的 url 在点击它时会得到更新,但页面没有被呈现
- r - R中的SOAP请求,带有WS-security,SOAPHandler