Python | Панды dataframe.nunique ()

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas dataframe.nunique() function return Series with number of distinct observations over requested axis. If we set the value of axis to be 0, then it finds the total number of unique observations over the index axis. If we set the value of axis to be 1, then it find the total number of unique observations over the column axis. It also provides the feature to exclude the NaN values from the count of unique numbers.

Syntax: DataFrame.nunique(axis=0, dropna=True)

Parameters :
axis : {0 or ‘index’, 1 or ‘columns’}, default 0
dropna : Don’t include NaN in the counts.

Returns : nunique : Series

Example #1: Use nunique() function to find the number of unique values over the column axis.

# importing pandas as pd
import pandas as pd
  
# Creating the first dataframe 
df = pd.DataFrame({"A":[14, 4, 5, 4, 1],
                   "B":[5, 2, 54, 3, 2],
                   "C":[20, 20, 7, 3, 8],
                    "D":[14, 3, 6, 2, 6]})
  
# Print the dataframe
df

Let’s use the dataframe.nunique() function to find the unique values across the column axis.

# find unique values
df.nunique(axis = 1)

Output :

As we can see in the output, the function prints the total no. of unique values in each row.
 
Example #2: Use nunique() function to find the number of unique values over the index axis in a dataframe. The dataframe contains NaN values.

# importing pandas as pd
import pandas as pd
  
# Creating the first dataframe 
df = pd.DataFrame({"A":["Sandy", "alex", "brook", "kelly", np.nan],
                   "B":[np.nan, "olivia", "olivia", "", "amanda"], 
                   "C":[20 + 5j, 20 + 5j, 7, None, 8],
                   "D":[14.8, 3, None, 6, 6]})
  
# apply the nunique() function
df.nunique(axis = 0, dropna = True)

Выход :

Функция обрабатывает пустую строку как уникальное значение в столбце 2.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.