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

基于时间偏移规则在DataFrame间匹配并新增利润列

DataFrame按规则匹配利润值的代码调整方案

背景

现有两个DataFrame:

  • df_rates:列名为时间戳(示例:'2012-03-31 23:45:00'),列值为对应利率;索引为Mins before time,代表该行数据对应的时间比列名时间提前的分钟数。
  • df_profit:索引为时间戳,包含Profit列存储利润值。

需求

在df_rates中新增New_column,按以下规则填充df_profit的Profit值:

  • 若df_rates的列名为'2012-03-31 23:45:00',找到df_profit中该时间戳提前30分钟(即'2012-03-31 23:15:00')对应的Profit值(-21.48),填充到Mins before time为0的行;
  • Mins before time为15的行,填充df_profit中时间更早的下一个Profit值(示例:'2012-03-31 23:00:00'对应的-8.538);以此类推,仅填充索引为0、15、30这类间隔15分钟的行,其余行留空。

现有代码问题

当前代码仅直接匹配「列名时间 - 行索引分钟数」对应的时间戳利润值,无法满足上述“依次取更早下一个利润值”的规则:

df_rates['New column'] = df_profit.Profit.reindex(pd.to_datetime(df_rates.columns[-1]) - pd.to_timedelta(df_rates['Mins before time'], unit='min')).to_numpy()

示例数据

df_rates

Mins before time     2012-03-31 23:45:00
0                        113.1
5                        112.1
10                       113.1
15                       113.17
20                       103.17
25                       133.17
30                       101.39

df_profit

Profit
2012-04-01 00:30:00      251.71
2012-04-01 00:15:00      652.782
2012-04-01 00:00:00      458.099
2012-03-31 23:45:00      3504.664
2012-03-31 23:30:00      1215.76
2012-03-31 23:15:00     -21.48
2012-03-31 23:00:00     -8.538
2012-03-31 22:40:00     -5.11

预期结果

Mins before time    2012-03-31 23:45:00   New_column
0                      113.1                     -21.48
5                      112.1    
10                     113.1    
15                     113.17                    -8.538
20                     103.17   
25                     133.17   
30                     101.39                    -5.11

调整方案

以下代码实现需求逻辑:

import pandas as pd

# 确保df_profit的索引为datetime类型
df_profit.index = pd.to_datetime(df_profit.index)

# 获取df_rates的目标时间列(多列场景可按需调整为columns[-1]或遍历列)
target_time = pd.to_datetime(df_rates.columns[0])
# 计算初始匹配时间:目标时间提前30分钟
initial_match_time = target_time - pd.Timedelta(minutes=30)

# 筛选df_profit中早于等于初始匹配时间的行,按时间降序排列(最新的在前)
filtered_profit = df_profit[df_profit.index <= initial_match_time].sort_index(ascending=False)

# 筛选需要填充的df_rates索引(间隔15分钟的索引)
target_indices = df_rates.index[df_rates.index % 15 == 0].tolist()
# 建立索引与利润值的顺序映射
mapping = {
    idx: filtered_profit['Profit'].iloc[i] 
    for i, idx in enumerate(target_indices) 
    if i < len(filtered_profit)
}

# 填充新列
df_rates['New_column'] = df_rates.index.map(mapping)

逻辑说明

  1. 先确定初始匹配时间:目标列时间提前30分钟;
  2. 从df_profit中筛选出早于等于该初始时间的所有利润数据,按时间降序排列,确保初始匹配时间的利润排在第一位,依次往后是更早的利润值;
  3. 将df_rates中间隔15分钟的索引(0、15、30...)与筛选后的利润值按顺序一一映射;
  4. 通过索引映射填充新列,未匹配的索引行自动留空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:05:21