[英]How to calculate the percentage of each value in a column follow each category in python pandas dataframe
I'm having a dataframe and trying to get the output which shows percentage of each value in different category.我有一个 dataframe 并试图获得 output ,它显示了不同类别中每个值的百分比。 Can anyone help on how can I do it?谁能帮助我怎么做?
Raw data table:原始数据表:
Interface_Bin接口_Bin | Product产品 |
---|---|
1 1 | ADL日常活动 |
1 1 | ADL日常活动 |
22 22 | ADL日常活动 |
97 97 | ADL日常活动 |
1 1 | JSL JSL |
1 1 | JSL JSL |
97 97 | JSL JSL |
97 97 | JSL JSL |
22 22 | JSL JSL |
Expected outcome:预期结果:
Product产品 | Bin(97)_count Bin(97)_count | Total_interfacebin_count Total_interfacebin_count | Bin_97_percentage_vs total count bin_97_percentage_vs 总计数 |
---|---|---|---|
ADL日常活动 | 1 1 | 4 4 | 25% 25% |
JSL JSL | 2 2 | 5 5 | 40% 40% |
Thanks alot.非常感谢。
first sort the data so you get a dictionary (or list) like: {"ADL":121,"JSL":218} probably with code like首先对数据进行排序,以便得到一个字典(或列表),例如: {"ADL":121,"JSL":218} 可能带有类似的代码
for element in table row:
if dict.contains(element.key) //in this case ADL or JSL
dict[element.key].value+=element.value
else
dict[element.key]=element.value
then go through and sum all the dictionary values to get the total sum, or sum them as you add to the dictionary in the above code finally get each percentage as (dict[key].value/sum)*100 + "%"然后 go 通过并求和所有字典值以获得总和,或者将它们加到上述代码中的字典中,最终得到每个百分比为 (dict[key].value/sum)*100 + "%"
Use crosstab
with concat
:将crosstab
与concat
一起使用:
df = pd.crosstab(df['Product'], df['Interface_Bin'])
f1 = lambda x: f'Bin({x})_count'
f2 = lambda x: f'Bin({x})_percentage_vs total count'
s = df.sum(axis=1).rename('Total_interfacebin_count')
df2 = df.div(s, axis=0).rename(columns=f2).mul(100)
df = pd.concat([df.rename(columns=f1), s, df2], axis=1).sort_index(axis=1)
print (df)
Bin(1)_count Bin(1)_percentage_vs total count Bin(22)_count \
Product
ADL 2 50.0 1
JSL 2 40.0 1
Bin(22)_percentage_vs total count Bin(97)_count \
Product
ADL 25.0 1
JSL 20.0 2
Bin(97)_percentage_vs total count Total_interfacebin_count
Product
ADL 25.0 4
JSL 40.0 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.