我有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

然后我用重采样df到30分钟-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

如何将新的第df_resample['High'] - df_resample['Low']列从df_resample插入到df?根据Date的值是什么小时

推荐答案

IIUC,您可以创建临时列,然后合并:

df1["date"] = df1.Date.dt.date
df1["hour"] = df1.Date.dt.hour

df2["date"] = df2.index.date
df2["hour"] = df2.index.hour

df2["Value"] = df2["High"] - df2["Low"]

df1 = df1.merge(df2[["date", "hour", "Value"]], on=["date", "hour"]).drop(
    columns=["date", "hour"]
)
print(df1)

打印:

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

Python相关问答推荐

Django:如何将一个模型的唯一实例创建为另一个模型中的字段

Pandas数据帧处理Pandas表中Json内的嵌套列表以获取后续Numpy数组

为什么我的主页不会重定向到详细视图(Django)

使用decorator 重复超载

Snap 7- read_Area用于类似地址的变量

Pandas read_jsonfuture 警告:解析字符串时,to_datetime与单位的行为已被反对

如何销毁框架并使其在tkinter中看起来像以前的样子?

将轨迹优化问题描述为NLP.如何用Gekko解决这个问题?当前面临异常:@错误:最大方程长度错误

计算所有前面行(当前行)中列的值

Python在tuple上操作不会通过整个单词匹配

沿着数组中的轴计算真实条目

如何访问所有文件,例如环境变量

Python,Fitting into a System of Equations

实现自定义QWidgets作为QTimeEdit的弹出窗口

根据列值添加时区

提取相关行的最快方法—pandas

Python Pandas获取层次路径直到顶层管理

在Python中使用if else或使用regex将二进制数据如111转换为001""

在pandas数据框中计算相对体积比指标,并添加指标值作为新列

ruamel.yaml dump:如何阻止map标量值被移动到一个新的缩进行?