Python Pandas——查詢列的最大值並返回其對應的行值


Pandas中尋找列的最大值並返回其對應的行值,我們可以使用df.loc[df[col].idxmax()]。讓我們舉個例子來加深理解。

步驟

  • 建立一個二維、尺寸可變、具有異構表格資料的 df
  • 列印輸入 DataFrame(資料框),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

修改日期:2023-08-27

29K+次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.