Python Forum
How to get count of each unique item in dataframe
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get count of each unique item in dataframe
#1
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()
Reply
#2
df.Age.value_counts()
Output:
Fail 2 Pass 2 Name: Age, dtype: int64
Reply
#3
I could do up to here, but I want to define the results as below:

Labels  values
Fail     2
Pass     2
Reply
#4
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
it gives error:
TypeError: rename_axis() got an unexpected keyword argument 'columns'
Reply
#6
(Aug-03-2019, 06:01 PM)SriMekala Wrote: Frenchman
Thank you
Reply
#7
(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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#8
pandas.__version__
Out[9]: '0.19.2'
python: 3.6.8.final.0
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to get first and last row index of each unique names in pandas dataframe SriRajesh 1 4,447 Oct-13-2018, 07:04 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020