Reputation: 1998
How can I use a filter for if a column is = for a value counts?
For example
If I have df column below as:
Column
Happy
Sad
Mad
Glad
Happy
Mad
Glad
Glad
I want to run a df['Column'].value_counts(normalize = True)
But I only want to see the % for Glad, this is a sample df, but the actual df as many volume values and instead of sifting through I just want to see the % for Glad for example. Thanks!
Upvotes: 1
Views: 1001
Reputation: 16683
Just add .loc['Glad']
to the end of your code, because value_counts()
creates a pandas series allowing you to filter for Glad
using loc
:
df['Column'].value_counts(normalize=True).loc['Glad']
0.375
OR you can use shape[0]
to get total rows of filtered dataframe for 'Glad'
values as a proportion of total rows of the full dataframe:
df[df['Column'] == 'Glad'].shape[0] / df.shape[0]
0.375
Upvotes: 3
Reputation: 133458
Could you please try following, written as per your shown samples, this will give all column's percentage here.
import pandas as pd
df['Column'].value_counts(normalize=True) * 100
OR taking inspiration from David answer to get string Glad's percentage only use .loc
for above solution.
df['Column'].value_counts(normalize=True).loc['Glad'] * 100
Upvotes: 2