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
Format pandas dataframe index date
提问by jake wong
I have a dataframe that I got from the below code, but I am unable to convert the date
index 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 date
as yyyy-mm-dd
它仍然打印出date
作为yyyy-mm-dd
回答by jezrael
If need DatetimeIndex
then is is problem, because yyyy-mm-dd
is default display format of dates
in pandas
.
如果需要DatetimeIndex
则是问题,因为yyyy-mm-dd
是dates
in 的默认显示格式pandas
。
If need string
index 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