Python 按布尔变量分组,并创建一个新列,其中包含每个组的结果
这可能有点混乱,但我有以下数据框:Python 按布尔变量分组,并创建一个新列,其中包含每个组的结果,python,pandas,dataframe,formula,Python,Pandas,Dataframe,Formula,这可能有点混乱,但我有以下数据框: exporter assets liabilities False 5 1 True 10 8 False 3 1 False 24 20 False 40 2 True 12 11 我想用这个公式计算一个比率df['liabilities'].sum()/df['assets'].sum(
exporter assets liabilities
False 5 1
True 10 8
False 3 1
False 24 20
False 40 2
True 12 11
我想用这个公式计算一个比率df['liabilities'].sum()/df['assets'].sum())*100
我希望创建一个新列,其中的值是比率,但为每个布尔值计算,如下所示:
exporter assets liabilities ratio
False 5 1 33.3
True 10 8 86.3
False 3 1 33.3
False 24 20 33.3
False 40 2 33.3
True 12 11 86.3
在列exporter
上使用sum
和transform
转换数据场,然后使用负债
除以资产
,并使用乘以100:
d = df.groupby('exporter').transform('sum')
df['ratio'] = d['liabilities'].div(d['assets']).mul(100).round(2)
结果:
print(df)
exporter assets liabilities ratio
0 False 5 1 33.33
1 True 10 8 86.36
2 False 3 1 33.33
3 False 24 20 33.33
4 False 40 2 33.33
5 True 12 11 86.36