Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas – Tìm giá trị lớn nhất của cột và trả về giá trị hàng tương ứng


Để tìm giá trị lớn nhất của một cột và trả về các giá trị hàng tương ứng trong Pandas, chúng ta có thể sử dụng df.loc[df[col].idxmax()]. Hãy lấy ví dụ để hiểu rõ hơn.

Các bước

  • Tạo dữ liệu bảng hai chiều, df.
  • In DataFrame đầu vào, df.
  • Khởi tạo biến col để tìm giá trị lớn nhất của cột đó.
  • Tìm giá trị lớn nhất và hàng tương ứng, sử dụng df.loc[df[col].idxmax()].
  • In kết quả bước 4.

Ví dụ

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)

Kết quả

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