peanut.head.hwc
peanut.head.hwc

Reputation: 7

Selecting a single value to groupby() in python

I have a dataframe with two columns. I only want the results of the Female gender.

This is my code:

fpl_sales = sales[['Gender', 'Product line']]
fpl_sales
fpl_sales.groupby(['Gender', 'Product line'])['Product line'].count()

This is my output:

Gender  Product line          
Female  Electronic accessories    84
        Fashion accessories       96
        Food and beverages        90
        Health and beauty         64
        Home and lifestyle        79
        Sports and travel         88
Male    Electronic accessories    86
        Fashion accessories       82
        Food and beverages        84
        Health and beauty         88
        Home and lifestyle        81
        Sports and travel         78
Name: Product line, dtype: int64

This is almost correct, however I only want the female portion of the output.

Thank you

Upvotes: 0

Views: 643

Answers (1)

Subbu VidyaSekar
Subbu VidyaSekar

Reputation: 2615

you can filter like in the second line of code.

pandas groupby with .filter:

fpl_sales.groupby(['Gender', 'Product line'])['Product line'].count().filter(lambda x: x['Gender']== 'Female')

Or

fpl_sales = sales[['Gender', 'Product line']]
fpl_sales = fpl_sales[fpl_sales['Gender'] == 'Female']
fpl_sales.groupby(['Gender', 'Product line'])['Product line'].count()

or

sales_count = fpl_sales.groupby(['Gender', 'Product line'])['Product line'].count()
sales_count[sales_count['Gender']=='Female']

Upvotes: 1

Related Questions