简体   繁体   中英

Pandas DataFrame.index.name is deleted by DataFrame.index.date

I am new to pandas and also still quite new to python so please bear with me. Here is the question:

I read some data from excel, including some dates. I use these dates as indexes and they are in the form %Y-%m-%d %H:%M:%S . But I need these indices in the form %Y-%m-%d . So I wrote

df.index = df.index.date # where df is a DataFrame object

I found out that after this df.index.name is "" , but it should be "Date" . It seems strange to me why the .name property should be changed/deleted after the .date conversion. I know I can simply put it back as df.index.name = "Date" , but is there any kind of explanation for this behaviour or is it a bug.

Thanks in advance.

So it looks like you just want to format the dates for output. Because of this, I'd recommend keeping the index as the DatetimeIndex and then just format it when writing. The to_csv() method has a date_format parameter that you can pass a strftime string.

In [21]: ts = pd.DataFrame(np.random.randn(20, 2), index=pd.DatetimeIndex(start='2014-01-01
', periods=20, freq='min'))


In [23]: ts.to_csv('tst.csv', date_format='%Y-%m-%d')

In [24]: !cat tst.csv
,0,1
2014-01-01,0.23269024172796468,-0.27276285241328363
2014-01-01,-2.1271569576784652,-0.08828528516158064
2014-01-01,-0.7476540707009801,0.4496366704379928
2014-01-01,-1.278025433730537,1.9559942454312738
2014-01-01,-0.5197557973521872,-0.38696497057942586
2014-01-01,1.907212175479462,0.08269395500820262
2014-01-01,-0.002980557062394977,1.649695381207261
2014-01-01,-0.9676320141522591,0.549518266575642
2014-01-01,-1.3499641850605548,-0.11695278340333974
2014-01-01,0.3281427666328896,0.2290718384099928
2014-01-01,0.29854271481529915,-1.606564949527949
2014-01-01,-1.8476324099199142,-1.1062031058677215
2014-01-01,-0.2625937089406767,0.6743539439246344
2014-01-01,0.1901494293074155,2.830381213725509
2014-01-01,-0.16171736635213055,-0.6913561112174935
2014-01-01,-0.6340530961142582,0.1944027320940862
2014-01-01,0.1875828513714546,0.3539781699433568
2014-01-01,1.502398492411021,0.9554844690144768
2014-01-01,0.40825706445611654,-0.6555754482696242
2014-01-01,-1.9870063518613181,0.8300825796678137

It doesn't look like to_excel() has a date_format option. You could file an issue/feature request on Github if you'd like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM