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

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

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

Pandas dataframe.mode() function gets the mode(s) of each element along the axis selected. Adds a row for each mode per label, fills in gaps with nan. Note that there could be multiple values returned for the selected axis (when more than one item share the maximum frequency), which is the reason why a dataframe is returned.

Syntax: DataFrame.mode(axis=0, numeric_only=False)
Parameters :
axis : get mode of each column1, get mode of each row
numeric_only : if True, only apply to numeric columns

Returns : modes : DataFrame (sorted)

Example #1: Use mode() function to find the mode over the index axis.

# importing pandas as pd
import pandas as pd
  
# Creating the 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

Lets use the dataframe.mode() function to find the mode of dataframe

# find mode of dataframe 
df.mode()

Выход :

 
Example #2: Use mode() function to find the mode over the column axis

# importing pandas as pd
import pandas as pd
  
# Creating the 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

Lets use the dataframe.mode() function to find the mode

# axis = 1 indicates over the column axis
df.mode(axis = 1)

Выход :

В 0-й и 3-й строке 14 и 3 - это режим, так как они имеют максимальное вхождение (т.е. 2). В остальной части столбца все элементы являются модными, потому что они имеют одинаковую частоту появления.

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

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