Python 重新调整列的比例,使之加起来等于1
我的当前列包含如下比例:Python 重新调整列的比例,使之加起来等于1,python,pandas,dataframe,data-manipulation,Python,Pandas,Dataframe,Data Manipulation,我的当前列包含如下比例: Name | Prop | US | 0.25 | UK | 0.30 | AUS | 0.45 | 增加了一行及其比例 Name | Prop | US | 0.25 | UK | 0.30 | AUS | 0.45 | DEN | 0.10 | 添加新行后计算列的新比例,以便调整其他行,保持新行的比例不变,且比例之和为1 Name | Prop | US |
Name | Prop |
US | 0.25 |
UK | 0.30 |
AUS | 0.45 |
增加了一行及其比例
Name | Prop |
US | 0.25 |
UK | 0.30 |
AUS | 0.45 |
DEN | 0.10 |
添加新行后计算列的新比例,以便调整其他行,保持新行的比例不变,且比例之和为1
Name | Prop |
US | x |
UK | x |
AUS | x |
DEN | 0.10 |
使用和:
编辑
vals_to_scale = df.loc[df.index[:-1], 'Prop']
df.loc[df.index[:-1], 'Prop'] = (vals_to_scale.div(vals_to_scale.sum())
.mul(1-df.loc[df.index[-1], 'Prop']))
print(df)
Name Prop
0 US 0.225
1 UK 0.270
2 AUS 0.405
3 DEN 0.100
这里我们用索引数据,你能解释一下这是怎么回事吗?我用序列中的每个项除以序列中的项之和,换句话说,就是值正在缩放以使总和为1。我假设你想要线性缩放汉克斯,你能用新的修改回答同样的问题吗(编辑了问题)
vals_to_scale = df.loc[df.index[:-1], 'Prop']
df.loc[df.index[:-1], 'Prop'] = (vals_to_scale.div(vals_to_scale.sum())
.mul(1-df.loc[df.index[-1], 'Prop']))
print(df)
Name Prop
0 US 0.225
1 UK 0.270
2 AUS 0.405
3 DEN 0.100