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

如何基于特定Underlying合并相同Trade Date的数据并求和?

按交易日期和标的合并DataFrame并汇总成交量

原始数据

Trade Date  Options Class   Underlying  Product Type    Volume
0   2022-01-03  A   A   S   14
1   2022-01-03  A   A   S   3
2   2022-01-03  A   A   S   42
3   2022-01-03  A   A   S   10
4   2022-01-03  AA  AA  S   1924

需求

按**交易日期(Trade Date)和标的(Underlying)**分组,合并相同分组内的行并汇总Volume字段。

问题分析

你写的代码错误在于groupby的参数传递:分组的多个列需要放在列表中,而非单独作为参数传入。直接传两个字符串会被解析为「第一个参数是分组列,第二个是axis轴参数」,导致逻辑错误或报错。

正确实现方法

方法1:仅汇总Volume字段

# 将分组列放入列表,指定只对Volume求和,再重置索引
result = df.groupby(['Trade Date', 'Underlying'])['Volume'].sum().reset_index()
print(result)

执行后输出:

Trade Date Underlying  Volume
0 2022-01-03          A      69
1 2022-01-03         AA    1924

方法2:保留其他字段(同组字段值一致时适用)

如果需要保留Options Class、Product Type这类非数值列,可使用agg指定每个字段的处理规则:

result = df.groupby(['Trade Date', 'Underlying']).agg(
    Volume=('Volume', 'sum'),
    Product_Type=('Product Type', 'first'),  # 取同组第一个值
    Options_Class=('Options Class', 'first')
).reset_index()
print(result)

执行后输出:

Trade Date Underlying  Volume Product_Type Options_Class
0 2022-01-03          A      69            S             A
1 2022-01-03         AA    1924            S            AA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:25:23