Python Pandas – Find the maximum value of a column and return its corresponding row values

PythonServer Side ProgrammingProgramming

To find the maximum value of a column and to return its corresponding row values in Pandas, we can use df.loc[df[col].idxmax()]. Let's take an example to understand it better.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
  • Print the input DataFrame, df.
  • Initialize a variable, col, to find the maximum value of that column.
  • Find the maximum value and its corresponding row, using df.loc[df[col].idxmax()]
  • Print the Step 4 output.

Example

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)
print "Input DataFrame is:\n", df

col = "x"
max_x = df.loc[df[col].idxmax()]
print "Maximum value of column ", col, " and its corresponding row values:\n", max_x

col = "y"
max_x = df.loc[df[col].idxmax()]
print "Maximum value of column ", col, " and its corresponding row values:\n", max_x

col = "z"
max_x = df.loc[df[col].idxmax()]
print "Maximum value of column ", col, " and its corresponding row values:\n", max_x

Output

Input DataFrame is:
  x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1

Maximum value of column x and its corresponding row values:
x  7
y  5
z  5
Name: 2, dtype: int64

Maximum value of column y and its corresponding row values:
x  2
y  7
z  3
Name: 1, dtype: int64

Maximum value of column z and its corresponding row values:
x  5
y  4
z  9
Name: 0, dtype: int64
raja
Published on 15-Sep-2021 06:42:15
Advertisements