Python Forum
How to get count of each unique item in dataframe - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: How to get count of each unique item in dataframe (/thread-20286.html)



How to get count of each unique item in dataframe - SriMekala - Aug-03-2019

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()



RE: How to get count of each unique item in dataframe - scidam - Aug-04-2019

df.Age.value_counts()
Output:
Fail 2 Pass 2 Name: Age, dtype: int64



RE: How to get count of each unique item in dataframe - SriMekala - Aug-04-2019

I could do up to here, but I want to define the results as below:

Labels  values
Fail     2
Pass     2



RE: How to get count of each unique item in dataframe - perfringo - Aug-05-2019

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



RE: How to get count of each unique item in dataframe - SriMekala - Aug-06-2019

it gives error:
TypeError: rename_axis() got an unexpected keyword argument 'columns'


RE: How to get count of each unique item in dataframe - chakrimakam - Aug-06-2019

(Aug-03-2019, 06:01 PM)SriMekala Wrote: Frenchman
Thank you


RE: How to get count of each unique item in dataframe - perfringo - Aug-06-2019

(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


RE: How to get count of each unique item in dataframe - SriMekala - Aug-06-2019

pandas.__version__
Out[9]: '0.19.2'
python: 3.6.8.final.0