在pandas数据帧中修改datetimeindex中的小时

时间:2015-09-08 08:38:48

标签: python pandas list-comprehension datetime-format

我有一个如下所示的数据框:

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]')

我需要做的是使用列中的小时更新索引中的小时,但以下方法不起作用:

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

如何进行?

2 个答案:

答案 0 :(得分:3)

IIUC我想你想构建一个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 进行比较:

PHP Fatal error:  Class '[obfuscated]'

你可以看到使用TimedeltaIndex明显更快

答案 1 :(得分: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')