简体   繁体   English

熊猫DataFrame.index.name被DataFrame.index.date删除

[英]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. 我是熊猫的新手,但是对python还是很新的,所以请多多包涵。 Here is the question: 这是问题:

I read some data from excel, including some dates. 我从excel中读取了一些数据,包括一些日期。 I use these dates as indexes and they are in the form %Y-%m-%d %H:%M:%S . 我将这些日期用作索引,它们的格式为%Y-%m-%d %H:%M:%S But I need these indices in the form %Y-%m-%d . 但是我需要这些索引以%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" . 我发现在此df.index.name"" ,但应为"Date" It seems strange to me why the .name property should be changed/deleted after the .date conversion. 在我看来,为什么在.date转换后应该更改/删除.name属性,这似乎很奇怪。 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. 我知道我可以简单地将其重新df.index.name = "Date"df.index.name = "Date" ,但是对此行为是否有任何解释或它是一个错误。

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. 因此,我建议将索引保留为DatetimeIndex ,然后在编写时对其进行格式化。 The to_csv() method has a date_format parameter that you can pass a strftime string. to_csv()方法具有date_format参数,您可以传递strftime字符串。

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. 看起来to_excel()似乎没有date_format选项。 You could file an issue/feature request on Github if you'd like. 您可以根据需要在Github上发布问题/功能请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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