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

Cách chọn hàng có giá trị lớn nhất theo nhóm trong Pandas DataFrame

Giới thiệu

Một trong những thao tác cơ bản và phổ biến nhất trong phân tích dữ liệu là chọn hàng chứa giá trị lớn nhất của một cột trong mỗi nhóm. Bài viết trình bày cách tìm giá trị lớn nhất của mỗi nhóm trong DataFrame.

Vấn đề

Giả sử bạn có tập dữ liệu phim và được yêu cầu liệt kê phim phổ biến nhất của mỗi năm dựa trên cột popularity.

Cách thực hiện

1. Chuẩn bị dữ liệu

Tải bộ dữ liệu phim từ Kaggle hoặc GitHub.


import pandas as pd
import numpy as np

movies = pd.read_csv("https://raw.githubusercontent.com/sasankac/TestDataSet/master/movies_data.csv")

2. Khám phá dữ liệu


# Xem 5 dòng ngẫu nhiên
print(movies.sample(n=5))

# Kiểm tra kiểu dữ liệu
print(movies.dtypes)

3. Tối ưu kiểu dữ liệu (tùy chọn)

Kiểm tra giá trị tối đa để quyết định có thể giảm kích thước kiểu dữ liệu (ví dụ: int64 → int16) cho cột vote_count, runtime.

4. Tạo cột năm từ release_date

Cột release_date kiểu object, cần chuyển đổi để nhóm theo năm.


movies['year'] = pd.to_datetime(movies['release_date']).dt.year.astype('Int64')

Phương pháp 1: Không dùng GroupBy (Sắp xếp + Loại bỏ trùng lặp)


# Chọn 3 cột cần thiết và sắp xếp
df_sorted = movies[["title", "year", "popularity"]].sort_values(["year", "popularity"], ascending=False)

# Giữ hàng đầu tiên của mỗi năm (phim phổ biến nhất)
result = df_sorted.drop_duplicates(subset="year")
print(result)

Phương pháp 2: Sử dụng GroupBy


result = (movies[["title", "year", "popularity"]]
          .groupby("year", as_index=False)
          .apply(lambda df: df.sort_values("popularity", ascending=False).head(1))
          .droplevel(0)
          .sort_values("year", ascending=False))
print(result)

Cách này gần với tư duy SQL:


SELECT title, year, popularity
FROM movies
WHERE popularity = (SELECT MAX(popularity) FROM movies m2 WHERE m2.year = movies.year)

Kết quả

Cả hai phương pháp cho kết quả tương tự: danh sách phim có độ phổ biến cao nhất mỗi năm (ví dụ: 2016: Deadpool, 2015: Minions, 2014: Interstellar...).