简体   繁体   中英

counting for specific value in pandas .value_counts()

I currently have a columns with two gender values, male = 1, and female = 2 and I would like to count and display the value next gender.

Gender = [1, 1, 1, 2, 1, 2, 2, 2, 1, 1, 2]

when I used this code

df['Gender'].value_counts() 

I got the following output:

1 6
2 5

Gender dType is int64

but I was looking for the following result. However I kept getting a different output than the following:-

The total number of Male: 6
The total number of Female: 5

This was print that I used but it kept giving me an error. I think I may need your help with this one. Thank you in advance.

print('The total number of Male:' df[Gender].value_counts(),'\n') 

value_counts returns the series. So you have to access a specific value by using position at which it is present, you can try the following:

Input 1 :

Gender = [1, 1, 1, 2, 1, 2, 2, 2, 1, 1, 2]
series = df['Gender'].value_counts() 
print(series)

Output 1 :

1    6
2    5
dtype: int64

Input : 2

print('The total number of Males : ', series[1])
print('The total number of Female : ', series[2]

Output 2

The total number of Males : 6
The total number of Females : 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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