【问题标题】:How to calculate sum f values in columns and percent of sum of these values and based on that create new columns in Python Pandas?如何计算列中的总和 f 值和这些值总和的百分比,并在此基础上在 Python Pandas 中创建新列?
【发布时间】:2021-08-12 15:07:39
【问题描述】:

Python Pandas 表中的 I 数据框如下所示:

col1 | col2
-----------
10   |2
20   |2
30   |1

我需要再创建 4 个列,例如:

  • col3 - col1 中每个值的总和

  • col4- col3 中值的百分比如何在 col1 中

  • col5 - col1 中每个值的总和

  • col6- col5 中值的百分比在 col2 中的百分比

因此,我需要如下所示:

col1  | col2 | col3 | col4 | col5 | col6
--------------------------------------
10    | 2    | 60   | 0,16 | 5    | 0.4
20    | 2    | 60   | 0.33 | 5    | 0.4 
30    | 1    | 60   | 0.5  | 5    | 0.2
  • col3 -> 因为 30+20+10 = 60
  • col4 -> 因为 10/60 = 0.16 等等
  • col5 -> 因为 2+2+1 = 5
  • col6 ->因为 2/5 = 0.4

【问题讨论】:

  • 你试过了吗?

标签: python pandas dataframe


【解决方案1】:

你可以通过for循环和extend()函数试试:

l=[]
for x in df:
    l.extend([[df[x].sum()]*len(df),(df[x]/df[x].sum()).tolist()])

最后从列表 l 中创建一个日期框,并使用 join() 方法将其与您的 df 加入:

idx=[f"{y}_sum" if x%2==0 else f"{y}_perc" for x,y in zip(range(len(df.columns)*2),df.columns.repeat(2))]
df=df.join(pd.DataFrame(l,index=idx).T)

df的输出:

   col1  col2  col1_sum  col1_perc  col2_sum  col2_perc
0    10     2      60.0   0.166667       5.0        0.4
1    20     2      60.0   0.333333       5.0        0.4
2    30     1      60.0   0.500000       5.0        0.2

【讨论】:

  • 好的,它可以工作,但是否可以代替 col.... 将其命名为 col1, col1_sum, col1_percent ?对于每列相同的逻辑?
  • 我看到了你最后的修改,但不是很好,但是差不多,因为我们可以假设我的列不是col1和col2,而是例如col1和dol1,我需要使用你的代码以及我需要 col1、col1_sum、col1_perc 和 dol1、dol1_sum、dol1_perc 的列的名称,这是我需要的最后一件事
  • @koler 是的,这就是我删除它的原因
  • @koler 现在尝试正确答案...请看一下:)
  • 哇!!现在它可以工作了,你是 Python 的大师 :D 但有趣的是,以前的解决方案适用于小型但不适用于真实的,但没关系,最重要的是最新的解决方案适用于我的真实数据:谢谢
猜你喜欢
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多