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

标签 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

如何进行?

最佳答案

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

关于python - 修改 pandas 数据框中的 datetimeindex 中的小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32453038/

相关文章:

python - 有没有办法通过对 2 张图像进行颜色处理来突出显示图像差异?

python - 如何为 gdb 安装 python 调试信息?

python - 将 pandas Series 替换为不同长度但相同索引的 Series

python - 按照特定的规则集计算一个新的数据框

python - 列表中所有对的乘积之和

python - 统计模型逻辑回归优势比

python - Django OneToOne 字段 self

python - 如何合并两列以上?

python - Pandas Dataframe 检查列值是否在列列表中

python - 在 python 列表理解中有没有一种方法可以不重复工作