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

如何按Strategy的P&L分组总和对多索引DataFrame的LS段排序?

按指定规则对多索引DataFrame的LS段排序

1. 初始DataFrame

import pandas as pd

df = pd.DataFrame({
    'Strategy': ['AAPL', 'AAPL', 'MSFT', 'MSFT', 'GOOGL','GOOGL', 'SPY'],
    'Attr':['LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'MH'],
    'Type': ['Equity', 'Swap', 'Equity', 'Put Option', 'Equity', 'Forward', 'Equity'],
    'P&L': [2131, -304, -988, -10, 91710, -80, 10000],
    'MV': [90000, -1000, 981231, -4000, 128123, -89, -900000]
})

2. 按Attr、Strategy、Type分组求和

执行分组求和代码:

grouped_df = df.groupby(['Attr', 'Strategy', 'Type'])['P&L', 'MV'].sum()

得到多索引结果:

P&L      MV
Attr Strategy Type        
LS   AAPL     Equity         2131    90000
               Swap           -304    -1000
     GOOGL    Equity         91710   128123
               Forward        -80      -89
     MSFT     Equity         -988   981231
               Put Option     -10    -4000
MH   SPY      Equity         10000  -900000

3. 确定排序依据

需按LS段各Strategy的P&L总和降序排序LS部分,先计算该排序依据:

ls_strategy_sorted = df.loc[df['Attr'] == 'LS'].groupby(['Strategy'])['P&L'].sum().sort_values(ascending=False)

计算结果:

Strategy
GOOGL    91630
AAPL      1827
MSFT      -998
Name: P&L, dtype: int64

4. 对多索引DataFrame的LS段排序

通过提取分段、重索引再合并的方式实现排序:

# 拆分LS和MH部分
ls_part = grouped_df.loc['LS']
mh_part = grouped_df.loc['MH']

# 按排序后的Strategy顺序重排LS部分索引
ls_part_sorted = ls_part.reindex(ls_strategy_sorted.index, level='Strategy')

# 合并恢复多索引结构
final_df = pd.concat([ls_part_sorted, mh_part], keys=['LS', 'MH'], names=['Attr'])

最终排序结果:

P&L      MV
Attr Strategy Type        
LS   GOOGL    Equity         91710   128123
               Forward        -80      -89
     AAPL     Equity         2131    90000
               Swap           -304    -1000
     MSFT     Equity         -988   981231
               Put Option     -10    -4000
MH   SPY      Equity         10000  -900000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:20:02