Encipher
Encipher

Reputation: 2866

How to Select Rows Based on Column Values in Pandas

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.

Upvotes: 2

Views: 518

Answers (3)

salman
salman

Reputation: 316

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

Upvotes: 2

wwnde
wwnde

Reputation: 26676

Please cross tabulate

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

Upvotes: 2

BehRouz
BehRouz

Reputation: 1364

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

Upvotes: 1

Related Questions