修改 pandas 数据框中 datetimeindex 中的小时

Modify hour in datetimeindex in pandas dataframe

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

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

如何进行?

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 明显更快

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