You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于小时将df_resample的高低差值列添加至原Pandas DataFrame?

将重采样后的小时波幅映射回原始Pandas DataFrame

问题背景

原始DataFrame(df):

Open      High       Low     Close     Volume                Date
3     25940.99  25972.27  25934.36  25938.65  176.08278 2023-08-23 02:20:00
4     25938.65  25938.65  25903.73  25921.67   67.24124 2023-08-23 02:25:00
5     25921.66  25963.83  25904.68  25951.51   83.37560 2023-08-23 02:30:00
6     25951.51  26011.07  25950.00  25998.00  119.22832 2023-08-23 02:35:00
7     25997.99  26050.50  25997.99  26015.14  242.94235 2023-08-23 02:40:00

重采样为60分钟粒度后的DataFrame(df_resample):

Open      High       Low     Close      Volume
Date
2023-08-23 02:00:00  25940.99  26070.04  25903.73  26056.00  1055.06782
2023-08-23 03:00:00  26055.99  26187.99  26030.56  26040.38  2447.77226
2023-08-23 04:00:00  26040.38  26081.64  25994.12  26049.41   728.81260
2023-08-23 05:00:00  26049.41  26091.75  26033.00  26044.42   795.45411
2023-08-23 06:00:00  26044.41  26078.01  25990.15  26006.32   764.41941

需求:基于Date列的小时信息,将df_resample['High'] - df_resample['Low']的计算结果作为新列插入到原始df中。

解决方案

步骤1:确保日期列是datetime类型

如果df和df_resample的日期列还不是datetime格式,先转换:

import pandas as pd

# 转换原始df的Date列
df['Date'] = pd.to_datetime(df['Date'])
# 将重采样后的索引转为列(方便后续操作)
df_resample = df_resample.reset_index()
df_resample['Date'] = pd.to_datetime(df_resample['Date'])

步骤2:计算小时波幅列

在df_resample中生成小时波幅列Hour_Range:

df_resample['Hour_Range'] = df_resample['High'] - df_resample['Low']

步骤3:映射波幅到原始df

这里提供两种简洁的实现方式:

方式1:使用map(推荐)

先将df_resample的波幅数据转为以小时起始时间为索引的Series,再通过原始df的小时起始时间映射:

# 生成以小时起始时间为索引的波幅Series
hour_range_map = df_resample.set_index('Date')['Hour_Range']
# 为原始df的每条数据匹配对应小时的波幅
df['Hour_Range'] = df['Date'].dt.floor('H').map(hour_range_map)

方式2:使用merge

通过合并操作关联两表的小时维度数据:

# 为原始df生成小时起始时间列
df['Hour_Start'] = df['Date'].dt.floor('H')
# 合并波幅数据
df = df.merge(df_resample[['Date', 'Hour_Range']], left_on='Hour_Start', right_on='Date', how='left')
# 删除临时生成的Hour_Start列(可选)
df = df.drop(['Hour_Start', 'Date_y'], axis=1).rename(columns={'Date_x': 'Date'})

最终结果示例

处理后的原始df会新增Hour_Range列,示例如下:

Open      High       Low     Close     Volume                Date  Hour_Range
3     25940.99  25972.27  25934.36  25938.65  176.08278 2023-08-23 02:20:00      166.31
4     25938.65  25938.65  25903.73  25921.67   67.24124 2023-08-23 02:25:00      166.31
5     25921.66  25963.83  25904.68  25951.51   83.37560 2023-08-23 02:30:00      166.31
6     25951.51  26011.07  25950.00  25998.00  119.22832 2023-08-23 02:35:00      166.31
7     25997.99  26050.50  25997.99  26015.14  242.94235 2023-08-23 02:40:00      166.31

内容的提问来源于stack exchange,提问作者Fresto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:12:09