【问题标题】:Group by a boolean variable and create a new column with the result for each group pandas按布尔变量分组并为每个组 pandas 创建一个包含结果的新列
【发布时间】:2020-07-28 06:41:14
【问题描述】:

这可能有点令人困惑,但我有以下数据框:

exporter assets   liabilities

False      5          1
True       10         8
False      3          1
False      24         20
False      40         2
True       12         11

我想用这个公式计算一个比率df['liabilieties'].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

【问题讨论】:

    标签: python pandas dataframe formula


    【解决方案1】:

    exportertransform 列上使用DataFrame.groupby 使用sum,然后使用Series.divliabilities 除以assets 并使用Series.mul 乘以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
    

    【讨论】:

      猜你喜欢
      • 2022-06-29
      • 1970-01-01
      • 2020-12-20
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2019-01-29
      相关资源
      最近更新 更多