ADVERTISEMENT
ADVERTISEMENT

How to find row where values for column is maximal in a Pandas DataFrame?

Given a Pandas DataFrame, we have to find row where values for column is maximal.
Submitted by Pranit Sharma, on May 18, 2022

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs. Here, we are going to find the row whose column has the maximum value.

For this purpose, pandas provide idx.max() method, which will return that index where the column value is max. Then with the help of pandas.DataFrame.loc property, we will get the row by passing the index.

Syntax:

DataFrame.idxmax(
    axis=0, 
    skipna=True
    )

Parameter(s): It takes two parameters, axis and skipna which are usually defined to check axis and to skip the Null values respectively.

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.

# Importing pandas package
import pandas as pd

# creating a dictionary 
d = {
    "Players":['Sachin','Ganguly','Dravid','Yuvraj','Dhoni','Kohli'],
    "Format":['ODI','ODI','ODI','ODI','ODI','ODI'],
    "Runs":[18426,11363,10889,8701,10773,12311]
}

# Now we will create DataFrame
df = pd.DataFrame(d)

# Viewing the DataFrame
print("Original DataFrame:\n",df,"\n\n")

# Find max Runs
result = df['Runs'].idxmax()

# Using df.loc
row = df.loc[result]

# Print row
print("Highest Runs:\n",row)

Output:

Example: Find row where values for column is maximal

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.