2015-09-08 43 views
2

我有一個數據幀,看起來像這樣:在大熊貓數據幀修改小時datetimeindex

master.head(5) 
Out[73]: 
      hour price 
day      
2014-01-01  0 1066.24 
2014-01-01  1 1032.11 
2014-01-01  2 1028.53 
2014-01-01  3 963.57 
2014-01-01  4 890.65 


In [74]: master.index.dtype 

Out[74]: dtype('<M8[ns]') 

我需要做的就是更新與該列中的小時指標小時,但下列方法不要」 t工作:

In [82]: master.index.hour = master.index.hour(master['hour']) 

TypeError: 'numpy.ndarray' object is not callable 

In [83]: master.index.hour = [master.index.hour(master.iloc[i,0]) for i in len(master.index.hour)] 

TypeError: 'int' object is not iterable 

如何繼續?

+0

你的預期結果是什麼? – styvane

+0

對不起,如果我不清楚,EdChum建議給出預期結果 – marpis

回答

3

IIUC我想你想構建一個TimedeltaIndex

In [89]: 
df.index += pd.TimedeltaIndex(df['hour'], unit='h') 
df 

Out[89]: 
        hour price 
2014-01-01 00:00:00  0 1066.24 
2014-01-01 01:00:00  1 1032.11 
2014-01-01 02:00:00  2 1028.53 
2014-01-01 03:00:00  3 963.57 
2014-01-01 04:00:00  4 890.65 

只是比較反對使用apply

In [87]: 
%timeit df.index + pd.TimedeltaIndex(df['hour'], unit='h') 
%timeit df.index + df['hour'].apply(lambda x: pd.Timedelta(x, 'h')) 

1000 loops, best of 3: 291 µs per loop 
1000 loops, best of 3: 1.18 ms per loop 

你可以看到,使用TimedeltaIndex是顯著快

+0

太棒了!我已經呆了一個小時,並沒有設法做到這一點! – marpis

+1

構建一個Timedeltaindex,會更快,發佈時間 – EdChum

+0

你甚至不需要明確地構造一個TimedeltaIndex,只是''df.index + pd.Timedelta('1h')'' – Jeff

0
master.index = 
pd.to_datetime(master.index.map(lambda x : x.strftime('%Y-%m-%d')) + '-' + master.hour.map(str) , format='%Y-%m-%d-%H.0') 
+0

不受支持的操作數類型爲+:'時間戳'和'str' – marpis

+0

您可能需要將「value '到字符串,檢查更新的答案 –

+0

有點上下文或解釋總是不錯... – DavidW