Coding Ref

How to find the mode in a Pandas DataFrame

How to find the mode in a Pandas DataFrame

To find the mode (i.e., the most frequently occurring value) in a Pandas DataFrame, you can use the mode() function.

This function returns the mode of each column in the DataFrame, as a Series with the same index as the original DataFrame.

Example

Here's an example of using the mode() function in Pandas to find the mode of a DataFrame:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3, 2, 3],
                   "B": [6, 7, 7, 8, 8]})

# find the mode of each column in the dataframe
df_mode = df.mode()

# display the result
print(df_mode)

This will find the mode of each column in the DataFrame, and return a new Series with the mode of each column.

The output will be:

output
   A  B
0  2  7
1  3  8

Find the mode of a column

You can also use the mode() function to find the mode of a particular column in a dataframe.

For example:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 2, 3],
                   'B': [1, 2, 3, 4],
                   'C': [1, 2, 2, 4]})

# find the mode of column A
mode_A = df['A'].mode()

# display the result
print(mode_A)

This will find the mode of column A and return it as a Series.

The resulting Series will contain the most common value(s) in column A.

In this case, the mode of column A is 2 because it appears twice in the column, which is more than any other value.

You'll also like

Related tutorials curated for you

    How to get the first row in Pandas

    How to stack two Pandas DataFrames

    How to give multiple conditions in loc() in Pandas

    What does Head() do in Pandas?

    How to get the number of columns in a Pandas DataFrame

    How to add an empty column to a Pandas DataFrame

    How to use qcut() in Pandas

    How to create a bar chart in Pandas

    What is .notnull in Pandas?

    How to read a TSV file in Pandas

    How to groupby mean in Pnadas

    What is date_range() in Pandas?