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

Pandas访问历史时序数据 基于前置条件计算新增profit列

Pandas 计算profit列实现方案

逻辑说明

你要求的计算规则可拆解为:

  • 当buyer为False时,profit计算公式为:- (price * qty)
  • 当buyer为True时,先取当前行之前最近的buyer=False行的price作为基准价,profit计算公式为:(当前行price - 基准价) * 当前行qty

实现代码

import pandas as pd

# 构造示例数据,实际使用时替换为自己的数据源即可
data = {
    'price': [2, 3, 4, 5],
    'qty': [4, 2, 2, 4],
    'buyer': [False, True, True, False]
}
df = pd.DataFrame(data, index=pd.to_datetime(['2021-11-06', '2021-11-07', '2021-11-08', '2021-11-09']))
df.index.name = 'time'

# 注意:必须保证数据按时间升序排列,若原始数据未排序先执行以下语句
# df = df.sort_index()

# 提取所有buyer=False行的价格,向前填充到后续所有行作为基准价
df['last_short_price'] = df['price'].where(~df['buyer']).ffill()

# 按规则计算profit
df['profit'] = df.apply(
    lambda row: -row['price'] * row['qty'] if not row['buyer'] 
    else (row['price'] - row['last_short_price']) * row['qty'],
    axis=1
)

# 可选:删除中间辅助列
df.drop('last_short_price', axis=1, inplace=True)

print(df)

输出结果验证

运行后得到的profit列和你给出的示例完全一致:

timepriceqtybuyerprofit
2021-11-0624False-8
2021-11-0732True2
2021-11-0842True4
2021-11-0954False-20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:06:09