Python Pandas - 查找列的最大值并返回其对应的行值

要在 Pandas 中查找列的最大值并返回其对应的行值,我们可以使用df.loc[df[col]。idxmax()]。让我们举一个例子来更好地理解它。

步骤

  • 创建二维、大小可变、潜在异构的表格数据 df。

  • 打印输入数据帧,df。

  • 初始化变量 col 以查找该列的最大值。

  • 使用 df.loc[df[col] 查找最大值及其对应的行。idxmax()]

  • 打印第 4 步的输出。

示例

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
输出结果
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