【问题标题】:Re- proportion pandas column with new adjustments to add up to 1重新调整 pandas 列与新的调整相加为 1
【发布时间】:2020-04-01 22:24:51
【问题描述】:

我当前的专栏包含这样的比例:

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 |

【问题讨论】:

    标签: python pandas dataframe data-manipulation


    【解决方案1】:

    使用Series.div 和Series.sum:

    df['Prop'] = df['Prop'].div(df['Prop'].sum())
    print(df)
    
      Name      Prop
    0   US  0.227273
    1   UK  0.272727
    2  AUS  0.409091
    3  DEN  0.090909
    
    #df['Prop'].sum() #checking now
    #1.0
    

    编辑

    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
    

    这里我们用DataFrame.loc[]索引数据

    【讨论】:

    • 你能解释一下这是做什么的吗?
    • 我将系列中的每个术语除以系列中术语的总和
    • 换句话说,值正在被缩放,使得总和为 1 线性。我以为你想要线性缩放
    • 谢谢,你能用新的修改帮助回答同样的问题吗(编辑问题)
    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 2021-09-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多