2

I create a dataset like that,

Gender    response
female    yes
male      yes
female    yes
female    no
male      yes
female    no
male      yes
male      no
female    no

I like to count the yes responses and no responses genderwise. Like there are two females who said No and 2 females who said yes. There are three males said yes and one said no.

I tried to implement this using pandas dataframe.

So far I have tried to write down the query like

df.loc[df['Gender'] == 'female' & (df['response'] == 'yes')]

But I got error. How could I write it down?

Thank you.

1
  • The error you are getting is because you missed putting the first condition inside a bracket. Anyways the line you are looking for is df.groupby(['Gender', 'response'], as_index=False).size() Commented Oct 29, 2022 at 6:04

3 Answers 3

2

You can use value_counts with groupby method like this:

df.groupby('Gender')['response'].value_counts()

Response:

Gender  response
female  no          3
        yes         2
male    yes         3
        no          1
Sign up to request clarification or add additional context in comments.

Comments

2

Please cross tabulate

pd.crosstab(df['Gender'], df['response']).reset_index()

Comments

1

You can group and count each category like this too:

counts = df.groupby(['Gender','response']).size()

print(counts['female']['yes']) # Show the number of females who responded yes

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.