2017-10-07 36 views
1

我有一個巨大的DataFrame,其中包含日期時間表示的整數形式的索引,例如20171001。我要做的是將表單(例如20171001)更改爲日期時間格式'2017-10-01'將熊貓指數從整數更改爲日期時間格式

爲了簡單起見,我生成了這樣一個數據幀。

>>> df = pd.DataFrame(np.random.randn(3,2), columns=list('ab'), index= 
[20171001,20171002,20171003]) 
>>> df 
      a   b 
20171001 2.205108 0.926963 
20171002 1.104884 -0.445450 
20171003 0.621504 -0.584352 
>>> df.index 
Int64Index([20171001, 20171002, 20171003], dtype='int64') 

如果我們將 'to_datetime' 到df.index,我們有怪異的結果:

>>> pd.to_datetime(df.index) 
DatetimeIndex(['1970-01-01 00:00:00.020171001', 
      '1970-01-01 00:00:00.020171002', 
      '1970-01-01 00:00:00.020171003'], 
      dtype='datetime64[ns]', freq=None) 

我要的是DatetimeIndex(['2017-10-01', '2017-10-02', '2017-10--3'], ...) 我如何管理這個問題?請注意,該文件是給出的。

回答

5

使用format %Y%m%dpd.to_datetime

pd.to_datetime(df.index, format='%Y%m%d') 
DatetimeIndex(['2017-10-01', '2017-10-02', '2017-10-03'], dtype='datetime64[ns]', freq=None) 

要分配df.index = pd.to_datetime(df.index, format='%Y%m%d')

+1

爽!我不知道我們可以用整數來做到這一點! – MaxU

+1

感謝Bharath,它的工作原理。格式似乎意味着輸入數據。完善。 – gnoejh

1

pd.to_datetime是這樣做的熊貓方式。但這裏有兩個選擇:

import datetime 
df.index = (datetime.datetime.strptime(str(i),"%Y%m%d") for i in df.index) 

import datetime 
df.index = df.index.map(lambda x: datetime.datetime.strptime(str(x),"%Y%m%d")) 
相關問題