首页 > 解决方案 > 创建计算百分比重复 N 次的新列

问题描述

我想知道如何计算这些列的百分比并将其保存在旁边的新列中 N 次。例子

d1 = [['0.00', '10','11','15'], ['2.99', '30','40','0'], ['4.99', '5','0','2']]

df1 = pd.DataFrame(d1, columns = ['Price', '1','2','3']) 

我希望以下操作遍历所有列(当然除了价格)

df1['1%'] = df1['1'] / df1['1'].sum() (I got an error when I tried this)

结果:

d2 = [['0.00', '10','0.22','11','0.2156','15','0.8823'], ['2.99', '30','0.66','40','0.7843','0','0'], ['4.99', '5','0.11','0','0','2','0.1176']]

df2 = pd.DataFrame(d2, columns = ['Price', '1','1%','2','2%','3','3%']) 

(列可以是 N 次,所以我需要遍历所有列)

标签: pythonpandas

解决方案


为了获得输出,您需要使用将字符串转换为数字pd.to_numeric

pd.concat([df1, df1.drop('Price',1).apply(lambda x: pd.to_numeric(x).div(pd.to_numeric(x).sum()))
               .rename(columns=lambda x: x+'%')], 1)

输出:

    Price   1   2   3   1%                2%          3%
0   0.00    10  11  15  0.222222    0.215686    0.882353
1   2.99    30  40  0   0.666667    0.784314    0.000000
2   4.99    5   0   2   0.111111    0.000000    0.117647

推荐阅读