gpt4 book ai didi

python - 如何根据条件迭代行和行组的百分比权重

转载 作者:行者123 更新时间:2023-12-01 07:11:49 24 4
gpt4 key购买 nike

我有一个如下所示的数据框。

我唯一没有的是“重量百分比”。我需要它从各自的总金额中获取每笔返回的权重(以立即进行的总金额为准)。

结构不一致。有时,某个帐户特定月份的总计可能有 3 个类别,有时可能有 4 或 5 个类别。

我需要迭代“每月 MV 列”并找到每个类别在其月份总数中的权重。

目前看起来像这样:

Return Date    Account    Category    Monthly MV    
7/31/2003 abcdef BOND 1.00
7/31/2003 abcdef CASH 0.50
7/31/2003 abcdef EQUITY 1.50
7/31/2003 abcdef TOTAL 3.00
8/30/2003 abcdef ALT 1.00
8/30/2003 abcdef BOND 1.00
8/30/2003 abcdef CASH 0.25
8/30/2003 abcdef EQUITY 2.50
8/30/2003 abcdef REAL 0.25
8/30/2003 abcdef TOTAL 5.00

它应该看起来像这样:

Return Date    Account    Category    Monthly MV    % of Weight
7/31/2003 abcdef BOND 1.00 0.33333
7/31/2003 abcdef CASH 0.50 0.1667
7/31/2003 abcdef EQUITY 1.50 0.5
7/31/2003 abcdef TOTAL 3.00 1.00
8/30/2003 abcdef ALT 1.00 0.20
8/30/2003 abcdef BOND 1.00 0.20
8/30/2003 abcdef CASH 0.25 0.05
8/30/2003 abcdef EQUITY 2.50 0.5
8/30/2003 abcdef REAL 0.25 0.05
8/30/2003 abcdef TOTAL 5.00 1.00

最佳答案

IIUC,您可以回填 TOTAL 行并简单地除以:

df['% of Weight'] = df['Monthly MV'].div(df['Monthly MV']
.where(df['Category'].eq('TOTAL'))
.bfill()
)

输出:

  Return Date Account Category  Monthly MV  % of Weight
0 7/31/2003 abcdef BOND 1.00 0.333333
1 7/31/2003 abcdef CASH 0.50 0.166667
2 7/31/2003 abcdef EQUITY 1.50 0.500000
3 7/31/2003 abcdef TOTAL 3.00 1.000000
4 8/30/2003 abcdef ALT 1.00 0.200000
5 8/30/2003 abcdef BOND 1.00 0.200000
6 8/30/2003 abcdef CASH 0.25 0.050000
7 8/30/2003 abcdef EQUITY 2.50 0.500000
8 8/30/2003 abcdef REAL 0.25 0.050000
9 8/30/2003 abcdef TOTAL 5.00 1.000000

关于python - 如何根据条件迭代行和行组的百分比权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58174168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com