Python Forum

Full Version: How to get count of each unique item in dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have below DataFrame:

data = {'Name':['Tom', 'nick', 'krish', 'jack'],
'Age':['Fail', 'Pass', 'Pass', 'Fail']}

I want to get the count of each unique item under column "Age"(for example here Pass & Fail). Finally summarize to:

Labels  values
Fail    2
Pass    2
I use below code, but I could get the count, but could not be able to arrange to the table as shown above.

#%%:
import pandas as pd
 
# intialise data of lists.
data = {'Name':['Tom', 'nick', 'krish', 'jack'],
        'Age':['Fail', 'Pass', 'Pass', 'Fail']}
 # Create DataFrame
df = pd.DataFrame(data)
data_cnt=df.groupby('Age').count()
df.Age.value_counts()
Output:
Fail 2 Pass 2 Name: Age, dtype: int64
I could do up to here, but I want to define the results as below:

Labels  values
Fail     2
Pass     2
It beats me why one want to do that but little modification of scidam solution will do:

>>> new = pd.DataFrame(df.Age.value_counts()).rename_axis(columns='Labels').rename(columns={'Age':'values'})
>>> new
Labels  values
Fail         2
Pass         2
it gives error:
TypeError: rename_axis() got an unexpected keyword argument 'columns'
(Aug-03-2019, 06:01 PM)SriMekala Wrote: [ -> ]Frenchman
Thank you
(Aug-06-2019, 12:39 PM)SriMekala Wrote: [ -> ]it gives error:
TypeError: rename_axis() got an unexpected keyword argument 'columns'

Update pandas. It’s changed in version 0.24
pandas.__version__
Out[9]: '0.19.2'
python: 3.6.8.final.0