Find the max of two or more columns with pandas?

Given a Pandas DataFrame, we have to find the max of two or more columns. By Pranit Sharma Last updated : September 23, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mainly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consists of rows, columns, and the data.

Pandas library is a phenomenal collection of numerous functions and methods which is able to do almost everything. Mathematical operations play an important role in data analysis.

Problem statement

Given a Pandas DataFrame, we have to find the max of two or more columns.

Finding the max of two or more columns with pandas

To find the maximum value between two or more columns, we will use the column names and find their difference by using the sub() method also we will find the absolute values by using abs() method.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python program to find the max of two or more columns with pandas

# Importing pandas package
import pandas as pd

# Importing reduce function
from functools import reduce

# Creating  DataFrames
df1 = pd.DataFrame({
    'Name':['Hari','Om'],
    'Hindi':[78,87],
    'English':[67,65]
})

# Display DataFrame
print("Created DataFrame:\n",df1,"\n")

# Finding the student who scored maximum marks
result = df1[:df1.Hindi.sub(df1.English).abs().idxmax()]

# Display Result
print("Winner:\n",result)

Output

The output of the above program is:

Example: Find the max of two or more columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.