【问题标题】:pandas normalization of groupby.sum熊猫归一化 groupby.sum
【发布时间】:2019-02-14 00:55:17
【问题描述】:

我有一个看起来像这样的 pandas 数据框:

      **I     SI     weights**
        1     3      0.3  
        2     4      0.2
        1     3      0.5
        1     5      0.5

我需要这样做:给定一个 I 值,考虑每个 SI 值并添加总重量。最后,对于每个实现,我应该有类似的东西:

             I = 1     SI = 3      weight = 0.8
                       SI = 5      weight = 0.5

             I = 2     SI = 4      weight = 0.2

这很容易通过调用 groupby 和 sum 来实现:

       name = ['I', 'SI','weight']
       Location = 'Simulationsdata/prova.csv'
       df = pd.read_csv(Location, names = name,sep='\t',encoding='latin1') 

       results = df.groupby(['I', 'real', 'SI']).weight.sum()

现在我希望将权重归一化为 1,这样它应该是这样的:

             I = 1     SI = 3      weight = 0.615
                       SI = 5      weight = 0.385

             I = 2     SI = 4      weight = 1

我试过了:

        for idx2, j in enumerate(results.index.get_level_values(1).unique()):
            norm = [float(i)/sum(results.loc[j]) for i in results.loc[j]]

但是当我尝试为每个 I 绘制 SI 的分布时,我发现 SI 也被归一化,我不希望这种情况发生。

附:这个问题与this one有关,但由于涉及到问题的另一个方面,我认为最好单独问一下

【问题讨论】:

    标签: pandas plot normalization pandas-groupby


    【解决方案1】:

    您应该能够将weight 列除以它自己的总和:

    # example data
    df
       I  SI   weight
    0  1   3      0.3
    1  2   4      0.2
    2  1   3      0.5
    3  1   5      0.5
    
    # two-level groupby, with the result as a DataFrame instead of Series:
    # df['col'] gives a Series, df[['col']] gives a DF
    res = df.groupby(['I', 'SI'])[['weight']].sum()
    res
           weight
    I SI         
    1 3       0.8
      5       0.5
    2 4       0.2
    
    # Get the sum of weights for each value of I,
    # which will serve as denominators in normalization
    denom = res.groupby('I')['weight'].sum()
    denom
    I
    1    1.3
    2    0.2
    Name: weight, dtype: float64
    
    # Divide each result value by its index-matched
    # denominator value
    res.weight = res.weight / denom
    res
            weight
    I SI          
    1 3   0.615385
      5   0.384615
    2 4   1.000000
    

    【讨论】:

    • 这不起作用,我需要对每个 I 的权重进行标准化,而不是在整个数据帧上。我想我必须遍历 Is
    • @FrancescoDiLauro,对不起,我错过了问题的那一部分。我已经相应地编辑了我的答案。
    • @FrancescoDiLauro 很高兴听到!
    猜你喜欢
    • 1970-01-01
    • 2016-10-22
    • 2014-08-18
    • 2018-06-21
    • 2021-12-26
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多