Count of unique value in column pandas [duplicate]

烂漫一生 提交于 2019-12-30 10:50:38

问题


I have a dataframe and I am looking at one column within the dataframe called names

array(['Katherine', 'Robert', 'Anne', nan, 'Susan', 'other'], dtype=object)

I am trying to make a call to tell me how many times each of these unique names shows up in the column, for example if there are 223 instances of Katherine etc. How do i do this? i know value_counts just shows 1 for each of these because they are the separate unique values


回答1:


If I understand you correctly, you can use pandas.Series.value_counts.

Example:

import pandas as pd
import numpy as np

s = pd.Series(['Katherine', 'Robert', 'Anne', np.nan, 'Susan', 'other'])

s.value_counts()

Katherine    1
Robert       1
other        1
Anne         1
Susan        1
dtype: int64

The data you provided only has one of each name - so here is an example with multiple 'Katherine' entries:

s = pd.Series(['Katherine','Katherine','Katherine','Katherine', 'Robert', 'Anne', np.nan, 'Susan', 'other'])

s.value_counts()

Katherine    4
Robert       1
other        1
Anne         1
Susan        1
dtype: int64

When applied to your Dataframe you will call this as follows:

df['names'].value_counts()



回答2:


You could use group by to achieve that:

df[['col1']].groupby(['col1']).agg(['count'])


来源:https://stackoverflow.com/questions/41665659/count-of-unique-value-in-column-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!