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

如何在Pandas DataFrame中添加新列:计算(entry_price+exit_price)*size

解决方案

直接通过Pandas的向量化运算即可快速添加目标计算列,无需逐行循环,代码示例如下:

import pandas as pd

# 构造你的原始DataFrame
df = pd.DataFrame({
    'ticker': ['APPL', 'TSLA'],
    'created_at': ['2023-05-29', '2023-05-29'],
    'entry_price': [1, 2],
    'exit_price': [4, 3],
    'direction': ['LONG', 'SHORT'],
    'size': [12, 32]
})

# 添加计算列(列名可自定义,这里用total_value示例)
df['total_value'] = (df['entry_price'] + df['exit_price']) * df['size']

执行后得到的DataFrame结果:

ticker created_at  entry_price  exit_price direction  size  total_value
0   APPL 2023-05-29            1           4      LONG    12           60
1   TSLA 2023-05-29            2           3     SHORT    32          160

注意事项

  • 这种向量化运算比手动遍历行效率高很多,适合处理大规模数据集
  • 若之前尝试循环实现失败,建议替换为这种方式
  • 新列名称可根据业务需求修改,比如改为position_value等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:52:05