說我有以下資料框
Strategy AssetClass Symbol Value Indicator
Strat1 OPT OPT_ABC1 50 -0.3
Strat1 OPT OPT_ABC2 50 1.5
Strat1 STK STK_ABC 50 2.7
Strat2 STK STK_XYZ 70 -3.8
Strat3 OPT OPT_MNO 25 10
我想制作以下內容:
Strategy AssetClass Symbol Value Indicator
Strat1 3.9
OPT 1.2
OPT_ABC1 50 -0.3
OPT_ABC2 50 1.5
STK 2.7
STK_ABC 50 2.7
Strat2 -3.8
STK -3.8
STK_XYZ 70 -3.8
Strat3 10
OPT 10
OPT_MNO 25 10
所以想法是用每個策略的總數重新排列資料,然后是 AssetClass,然后是每個符號。“值”列在符號級別可用,而“指標”列是子組的總和。
我想過使用 pd.pivot_table 但它似乎沒有產生我正在尋找的總計/子總計。我想我應該在 Strategy 上使用/回圈 pd.groupby,然后在 Strategy/AssetClass 上回圈另一個 groupby,然后在 Strategy/AssetClass/Symbol 上回圈一個 groupby
df 是上面的資料框,我這樣做了:
container = []
for label, _df in df.groupby(['Strategy', 'AssetClass', 'Symbol']):
_df.loc[f'{label}'] = _df[['Indicator']].sum()
container.append(_df)
df_res = pd.concat(container)
print(df_res.fillna(''))
我的問題是在相應行之后插入小計,并且標簽用作索引。此外,我想不出添加其他 lopps 的簡單/pythonic 方式(即小計)
uj5u.com熱心網友回復:
您可以按不同的列進行聚合,因此為了提高性能,最好不要使用嵌套groupby.apply聚合,而是使用多重聚合,最后將它們連接在一起 by concat,更改列的順序 byDataFrame.reindex和每前 2 列的最后排序:
df1 = df.groupby(['Strategy', 'AssetClass', 'Symbol'], as_index=False).sum()
df2 = (df1.groupby(['Strategy', 'AssetClass'], as_index=False)['Indicator'].sum()
.assign(Symbol = ''))
df3 = (df1.groupby('Strategy', as_index=False)['Indicator'].sum()
.assign(AssetClass = ''))
df = (pd.concat([df3, df2, df1])
.reindex(df.columns, axis=1)
.fillna('')
.sort_values(['Strategy','AssetClass'], ignore_index=True))
print (df)
Strategy AssetClass Symbol Value Indicator
0 Strat1 3.9
1 Strat1 OPT 1.2
2 Strat1 OPT OPT_ABC1 50.0 -0.3
3 Strat1 OPT OPT_ABC2 50.0 1.5
4 Strat1 STK 2.7
5 Strat1 STK STK_ABC 50.0 2.7
6 Strat2 -3.8
7 Strat2 STK -3.8
8 Strat2 STK STK_XYZ 70.0 -3.8
9 Strat3 10.0
10 Strat3 OPT 10.0
11 Strat3 OPT OPT_MNO 25.0 10.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434031.html
標籤:python-3.x 熊猫 数据框 熊猫-groupby
上一篇:在列之間查找字串匹配
