+4 votes
in Programming Languages by (60.0k points)
I want to count the number of unique elements in each column of a dataframe. Which function should I use for it?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

The nunique() function of Pandas returns the count of distinct elements in the specified axis. If you want to find the count of unique elements in each column, do not specify any axis in the function.

Here is an example:

>>> import pandas as pd
>>> df = pd.DataFrame({'A':[1,2,3,4,3,2], 'B':[11,21,3,21,3,11]})
>>> df
   A   B
0  1  11
1  2  21
2  3   3
3  4  21
4  3   3
5  2  11
>>> df.nunique()
A    4
B    3
dtype: int64
 


...