Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

python - Format pandas dataframe index date

I have a dataframe that I got from the below code, but I am unable to convert the date index to 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.

it still prints out the date as yyyy-mm-dd

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If need DatetimeIndex then is is problem, because yyyy-mm-dd is default display format of dates in pandas.

If need string index by 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...