将 DateTimeIndex 列标题转换为日期

问题描述

我有一个数据框,它使用 DateTimeIndex 作为列标题。这些当前以 2021-05-01 00:00:00 的格式显示。我怎样才能摆脱“00:00:00”?

我在 SO 上查找了一些类似的问题,一般的回答是使用 .dt.date:

df.columns = df.columns.dt.date

但它给出了错误 AttributeError: 'DatetimeIndex' object has no attribute 'dt'。

我有什么问题吗,还是 .dt 对我的日期格式不起作用?

解决方法

使用DatetimeIndex.date

df.columns = df.columns.date

因为 .dt 用于处理列 (Series):

df['col'] = df['col'].dt.date

ser = ser.dt.date