[英]Pandas Calculate percentage by column values
The dataframe is like below dataframe 如下所示
id ![]() |
age![]() |
---|---|
a![]() |
30-40 ![]() |
b ![]() |
30-40 ![]() |
c ![]() |
30-40 ![]() |
d ![]() |
40-50 ![]() |
e ![]() |
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 ![]() |
60.00% ![]() |
40-50 ![]() |
40.00% ![]() |
Use Series.value_counts
with normalize=True
, then multiple by 100
and change format to DataFrame
:使用
Series.value_counts
和normalize=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.