【问题标题】:how to get percentage of columns to sum of row in python [duplicate]如何在python中获取列的百分比与行的总和[重复]
【发布时间】:2020-12-24 06:46:54
【问题描述】:

我有超过 100 列的高维数据。例如,我分享它的简化版本,如下所示:

date    product price   amount
11/17/2019  A   10  20
11/24/2019  A   10  20
12/22/2020  A   20  30
15/12/2019  C   40  50
02/12/2020  C   40  50

我正在尝试根据如下所示的总行总和计算列的百分比:

date    product price   amount
11/17/2019  A   10/(10+20)  20/(10+20)
11/24/2019  A   10/(10+20)  20/(10+20)
12/22/2020  A   20/(20+30)  30/(20+30)
15/12/2019  C   40/(40+50)  50/(40+50)
02/12/2020  C   40/(40+50)  50/(40+50)

有没有什么方法可以有效地处理高维数据?谢谢。

【问题讨论】:

    标签: python-3.x pandas pandas-groupby percentage


    【解决方案1】:

    除了提供的链接 (Normalize rows of pandas data frame by their sums),您还需要找到特定的列,因为您的前两列不是数字:

    cols = df.columns[2:]
    df[cols] = df[cols].div(df[cols].sum(axis=1), axis=0)
    Out[1]: 
             date product              price             amount
    0  11/17/2019       A 0.3333333333333333 0.6666666666666666
    1  11/24/2019       A 0.3333333333333333 0.6666666666666666
    2  12/22/2020       A                0.4                0.6
    3  15/12/2019       C 0.4444444444444444 0.5555555555555556
    4  02/12/2020       C 0.4444444444444444 0.5555555555555556
    

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2019-09-13
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多