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

如何在Pandas DataFrame中对符合条件的行执行配对条件运算?

需求与解决方案

问题场景

现有记录产品10个时间点价格和库存的Pandas DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame(index=np.arange(10))
df['price'] = [10,10,11,15,20,10,10,11,15,20]
df['stock'] = [30,20,13,8,4,30,20,13,8,4]

DataFrame内容如下:

price  stock
0     10     30
1     10     20
2     11     13
3     15      8
4     20      4
5     10     30
6     10     20
7     11     13
8     15      8
9     20      4

需要实现:

  • 匹配最近一次库存低于5的事件与对应最近的库存超过25的事件
  • 计算每对事件的价格变化(库存低事件价格 - 库存高事件价格)
  • 适配大规模数据集,避免手动挑选行

解决方案

利用pd.merge_asof按时间顺序自动配对事件,代码如下:

# 提取库存>25的起始事件,保留索引和价格
start_events = df[df['stock'] > 25].reset_index().rename(columns={
    'index': 'start_idx',
    'price': 'start_price'
})

# 提取库存<5的结束事件,保留索引和价格
end_events = df[df['stock'] < 5].reset_index().rename(columns={
    'index': 'end_idx',
    'price': 'end_price'
})

# 按索引顺序,为每个结束事件匹配最近的、索引更早的起始事件
matched_pairs = pd.merge_asof(
    end_events,
    start_events,
    left_on='end_idx',
    right_on='start_idx',
    direction='backward'  # 找最近的后方(更早的)起始事件
)

# 计算价格变化
matched_pairs['price_change'] = matched_pairs['end_price'] - matched_pairs['start_price']

# 输出结果
print(matched_pairs[['start_idx', 'end_idx', 'start_price', 'end_price', 'price_change']])

输出结果

start_idx  end_idx  start_price  end_price  price_change
0          0        4           10         20            10
1          5        9           10         20            10

逻辑说明

  • merge_asof是Pandas专为时序数据匹配设计的工具,能高效处理大规模数据集
  • direction='backward'确保每个结束事件只会匹配在它之前发生的最近起始事件,完全符合需求中的配对规则,不会出现交叉配对

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:42:28