Pandas DataFrame function nunique() in Python
The Pandas DataFrame function nunique() used to count the number of distinct elements in the given axis. It returns Series object that includes the unique distinct elements.
Syntax
 1 DataFrame.nunique(axis = 0, dropna = True)
axis : It is an integer or string that determine whether to compare by the index (0 or 'index') or columns. (1 or 'columns').
dropna : It expects a boolean value that specifies whether to include NaN in the count. If not specified the default value will be True.
nunique() function
 1 import pandas as pd
 2 import numpy as np
 3 
 4 df = pd.DataFrame(
 5             {'x': [1, 4, 2, 1, 4],
 6              'y': [1, 1, np.nan, 1, 4]})
 7 
 8 res1 = df.nunique()
 9 print('The distinct elements of dataframe :')
 10 print(res1)
In the above example, a dataframe object is created by passing dictionary object. A nunique() function is called that counts the distinct elements on indexes and assign result to the variable that will be printed on console.
Output
 1 The distinct elements of dataframe :
 2 x    3
 3 y    2
 4 dtype: int64

nunique() with axis and dropna

nunique() with axis and dropna
 1 import pandas as pd
 2 import numpy as np
 3 
 4 df = pd.DataFrame(
 5             {'x': [1, 4, 2, 1, 4],
 6              'y': [1, 1, np.nan, 1, 4]})
 7 
 8 res1 = df.nunique(axis = 1, dropna = False)
 9 print('The distinct elements of dataframe :')
 10 print(res1)
In the above example, a nunique() function is called by passing axis and dropna argument that count on columns by skipping NA. The result is assigned to the variable that will be printed on console.
Output
 1 The distinct elements of dataframe :
 2 0    1
 3 1    2
 4 2    2
 5 3    1
 6 4    1
 7 dtype: int64
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us