【问题标题】:pandas divide row value by aggregated sum with a condition set by other cell熊猫将行值除以聚合总和,条件由其他单元格设置
【发布时间】:2017-01-16 05:02:53
【问题描述】:

您好希望得到一些帮助,我有两列 Dataframe df 作为;

Source ID
1      2
2      3
1      2
1      2
1      3
3      1

我的目的是将源分组并根据分组的源将 ID 单元格除以总数,并将其附加到原始数据框,以便新列看起来像;

   Source ID  ID_new
    1      2  2/9
    2      3  3/3
    1      2  2/9
    1      2  2/9
    1      3  3/9
    3      1  3/1

我已经做到了;

df.groupby('Source ID')['ID'].sum()

要获得ID 的总数,但我不确定下一步该去哪里。

【问题讨论】:

    标签: python pandas dataframe group-by


    【解决方案1】:

    试试这个:

    In [79]: df.assign(ID_new=df.ID/df.groupby('Source').ID.transform('sum'))
    Out[79]:
       Source  ID    ID_new
    0       1   2  0.222222
    1       2   3  1.000000
    2       1   2  0.222222
    3       1   2  0.222222
    4       1   3  0.333333
    5       3   1  1.000000
    

    如果你需要它作为一个新的 persistent 列,你可以按照@jezrael 在comment 中提出的建议:

    In [81]: df['ID_new'] = df.ID/df.groupby('Source').ID.transform('sum')
    
    In [82]: df
    Out[82]:
       Source  ID    ID_new
    0       1   2  0.222222
    1       2   3  1.000000
    2       1   2  0.222222
    3       1   2  0.222222
    4       1   3  0.333333
    5       3   1  1.000000
    

    【讨论】:

    • 嗯,也许你可以在没有assign的情况下添加经典方式:)
    • df['ID_new']=df.ID/df.groupby('Source').ID.transform('sum')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2015-01-03
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多