The mode()
method in Pandas returns the mode(s) of a dataset, which represents the most frequently occurring value(s) in the data.
Example
import pandas as pd
# sample DataFrame
data = {'A': [1, 2, 2, 3, 4],
'B': [5, 5, 6, 6, 6]}
df = pd.DataFrame(data)
# calculate the mode for each column
modes = df.mode()
print(modes)
'''
Output
A B
0 2 6
'''
mode() Syntax
The syntax of the mode()
method in Pandas is:
df.mode(axis=0, numeric_only=False, dropna=True)
mode() Arguments
The mode()
method has the following arguments:
axis
(optional): specifies the axis along which to calculate the mode(s)numeric_only
(optional): ifTrue
, only numeric data will be considered when calculating the modedropna
(optional): ifFalse
,NaN
values will also be considered
mode() Return Value
The mode()
method returns a DataFrame containing the mode(s) for each column. If there are multiple modes in a column, all of them will be included in the result.
Example 1: Mode for Each Column
import pandas as pd
# sample DataFrame
data = {'A': [1, 2, 2, 3, 4],
'B': [5, 5, 6, 6, 6]}
df = pd.DataFrame(data)
# calculate the mode for each column
modes = df.mode()
print(modes)
Output
A B 0 2 6
In this example, we calculated modes for each column. The modes for A
and B
columns are 2 and 6 respectively because they are the values with highest frequency.
Example 2: Mode for Each Row
import pandas as pd
# sample DataFrame
data = {'A': [1, 2, 3, 4, 5],
'B': [1, 3, 5, 7, 9],
'C': [1, 2, 5, 4, 9]}
df = pd.DataFrame(data)
# calculate the mode for each row
modes = df.mode(axis=1)
print(modes)
Output
0 0 1 1 2 2 5 3 4 4 9
In this example, we calculated modes for each row using the axis=1
argument.