pandas 格式化熊猫数据框索引日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42185328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:57:43  来源:igfitidea点击:

Format pandas dataframe index date

pythonpandasdatetime

提问by jake wong

I have a dataframe that I got from the below code, but I am unable to convert the dateindex to dd/mm/yyyy

我有一个从下面的代码中获得的数据框,但我无法将date索引转换为 dd/mm/yyyy

df= pandas.read_html(base_url, header=0, index_col='Date', parse_dates=True)[0]
df.index = pandas.to_datetime(df.index, dayfirst=True)

This is the result

这是结果

            Col1  Col2   
Date                                          
2017-02-10  val1  val1  
2017-02-09  val2  val2  
2017-02-08  val3  val3  
2017-02-07  val4  val4  

I have tired a couple of other different variations that I searched for on stackoverflow, but i'm not able to find a combination that works.

我已经厌倦了在 stackoverflow 上搜索的其他几个不同的变体,但我找不到有效的组合。

it still prints out the dateas yyyy-mm-dd

它仍然打印出date作为yyyy-mm-dd

回答by jezrael

If need DatetimeIndexthen is is problem, because yyyy-mm-ddis default display format of datesin pandas.

如果需要DatetimeIndex则是问题,因为yyyy-mm-dddatesin 的默认显示格式pandas

If need stringindex by DatetimeIndex.strftime:

如果需要string索引DatetimeIndex.strftime

df.index = df.index.strftime('%d/%m/%Y')
print (df)
            Col1  Col2
10/02/2017  val1  val1
09/02/2017  val2  val2
08/02/2017  val3  val3
07/02/2017  val4  val4

print (type(df.index[0]))
<class 'str'>

Unfortunately this does not work - docs:

不幸的是,这不起作用 -文档

with pd.option_context('display.date_dayfirst', True):
    print (df)

            Col1  Col2
Date                  
2017-02-10  val1  val1
2017-02-09  val2  val2
2017-02-08  val3  val3
2017-02-07  val4  val4