简体   繁体   English

Pandas 按列值计算百分比

[英]Pandas Calculate percentage by column values

The dataframe is like below dataframe 如下所示

id ID age年龄
a一个 30-40 30-40
b b 30-40 30-40
c c 30-40 30-40
d d 40-50 40-50
e e 40-50 40-50

The count of '30-40' is 3, the count of '40-50' is 2. The output I want is just value, I don't care about the format. '30-40'的计数是3,'40-50'的计数是2。我想要的output只是值,我不在乎格式。 Here is the output这是 output

age年龄 percentage百分比
30-40 30-40 60.00% 60.00%
40-50 40-50 40.00% 40.00%

Use Series.value_counts with normalize=True , then multiple by 100 and change format to DataFrame :使用Series.value_countsnormalize=True ,然后乘以100并将格式更改为DataFrame

df1 = (df['age'].value_counts(normalize=True)
                .mul(100)
                .rename_axis('age')
                .reset_index(name='percentage'))
print (df1)
     age  percentage
0  30-40        60.0
1  40-50        40.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM