gpt4 book ai didi

python - 创建计算百分比重复 N 次的新列

转载 作者:行者123 更新时间:2023-12-01 00:35:21 25 4
gpt4 key购买 nike

我想知道如何计算这些列的百分比并将其保存在旁边的新列中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 次,所以我需要迭代所有列)

最佳答案

IIUC,您需要:

m=df1.set_index('Price').div(df1.set_index('Price').sum()).add_suffix('%')
df2=pd.concat([df1.set_index('Price'),m],axis=1).sort_index(axis=1).reset_index()
<小时/>
   Price   1        1%   2        2%   3        3%
0 0.00 10 0.222222 11 0.215686 15 0.882353
1 2.99 30 0.666667 40 0.784314 0 0.000000
2 4.99 5 0.111111 0 0.000000 2 0.117647

注意:这是假设数据类型是:

df1.dtypes
Price float64
1 int32
2 int32
3 int32

关于python - 创建计算百分比重复 N 次的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com