更改数据帧索引中的日期格式时出错

ge0*_*rge 4 pandas

我有以下 df :

                  A         B
2018-01-02  100.000000  100.000000
2018-01-03  100.808036  100.325886
2018-01-04  101.616560  102.307700
Run Code Online (Sandbox Code Playgroud)

我期待更改索引的时间格式,所以我尝试了(在链接Format pandas dataframe index date 中使用 @jezrael 的响应):

df.index = rdo.index.strftime('%d-%m-%Y')
Run Code Online (Sandbox Code Playgroud)

但它输出:

AttributeError: 'Index' object has no attribute 'strftime'
Run Code Online (Sandbox Code Playgroud)

我想要的输出是:

                 A         B
02-01-2018  100.000000  100.000000
03-01-2018  100.808036  100.325886
04-01-2018  101.616560  102.307700
Run Code Online (Sandbox Code Playgroud)

我发现上面链接中提出的问题与我的问题非常相似。我真的不明白为什么会出现 attrError 。

Max*_*axU 9

您的索引似乎是string( object) dtype,但它必须是 a DatetimeIndex,可以使用df.info()以下方法检查:

In [19]: df.index = pd.to_datetime(df.index).strftime('%d-%m-%Y')

In [20]: df
Out[20]:
                     A           B
02-01-2018  100.000000  100.000000
03-01-2018  100.808036  100.325886
04-01-2018  101.616560  102.307700
Run Code Online (Sandbox Code Playgroud)