Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas – Find the maximum value of a column and return its corresponding row values
To find the maximum value of a column and return its corresponding row values in Pandas, we can use df.loc[df[col].idxmax()]. This method first finds the index of the maximum value using idxmax(), then uses loc[] to retrieve the entire row.
Syntax
df.loc[df[column_name].idxmax()]
Where:
- df − The DataFrame
- column_name − The column to find the maximum value in
- idxmax() − Returns the index of the maximum value
- loc[] − Selects the row by index
Example
Let's create a DataFrame and find the maximum values for different columns ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print("Input DataFrame:")
print(df)
Input DataFrame: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1
Finding Maximum in Column 'x'
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
col = "x"
max_row = df.loc[df[col].idxmax()]
print("Maximum value of column", col, "and its corresponding row values:")
print(max_row)
Maximum value of column x and its corresponding row values: x 7 y 5 z 5 Name: 2, dtype: int64
Finding Maximum in Multiple Columns
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
# Check maximum for all columns
for col in ["x", "y", "z"]:
max_row = df.loc[df[col].idxmax()]
print(f"Column '{col}' maximum (value={max_row[col]}) at index {df[col].idxmax()}:")
print(max_row)
print()
Column 'x' maximum (value=7) at index 2: x 7 y 5 z 5 Name: 2, dtype: int64 Column 'y' maximum (value=7) at index 1: x 2 y 7 z 3 Name: 1, dtype: int64 Column 'z' maximum (value=9) at index 0: x 5 y 4 z 9 Name: 0, dtype: int64
Alternative Methods
| Method | Usage | Returns |
|---|---|---|
df.loc[df[col].idxmax()] |
Get entire row with max value | Series (full row) |
df[col].max() |
Get only the maximum value | Scalar value |
df[col].idxmax() |
Get index of maximum value | Index label |
Conclusion
Use df.loc[df[col].idxmax()] to find the maximum value in a column and retrieve the complete corresponding row. This method combines idxmax() to find the index and loc[] to access the full row data efficiently.
Advertisements
