Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python - Count the number of males and females in a csv file

Suppose I have this csv file named sample.csv:

CODE     AGE     SEX     CITY
----     ---     ---     ----
E101      25      M      New York
E102      42      F      New York
E103      31      M      Chicago
E104      67      F      Chicago

I wish to count the number of males and females in the data. For instance, for this one, the answer would be:

M : 2
F : 2

Where should I start and how should I code it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this:

import pandas as pd
df = pd.read_csv("sample.csv")

print(f"M : {len(df[df['SEX'] == 'M'])}")
print(f"F : {len(df[df['SEX'] == 'F'])}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...