How to Select Rows Based on Column Values in Pandas

Question:

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.

Asked By: Encipher

||

Answers:

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
Answered By: BehRouz

Please cross tabulate

pd.crosstab(df['Gender'], df['response']).reset_index()
Answered By: wwnde

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
Answered By: salman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.