如何在 Python Pandas DataFrame 中选择每个组中的最大值?

pythonserver side programmingprogramming更新于 2026/2/15 5:32:17

简介

数据分析期间执行的最基本和最常见的操作之一是选择包含组中某些列的最大值的行。在这篇文章中,我将向您展示如何在 DataFrame 中找到每个组中的最大值。

问题..

首先让我们了解一下这个任务,假设您获得了一个电影数据集,并被要求根据受欢迎程度列出每年最受欢迎的电影。

怎么做..

1.准备数据。

好吧,Google 上有很多数据集。我经常使用 kaggle.com 获取数据分析所需的数据集。请随时登录 kaggle.com 并搜索电影。将电影数据集下载到目录并将其导入 Pandas DataFrame。

如果你和我一样从 kaggle.com 下载了数据,请点赞帮助你处理数据的人。

import pandas as pd
import numpy as np
movies = pd.read_csv("https://raw.githubusercontent.com/sasankac/TestDataSet/master/movies_data.csv")
# 查看示例 5 行
print(f"Output \n\n*** {movies.sample(n=5)} ")

输出

*** budget id original_language original_title popularity \
2028 22000000 235260 en Son of God 9.175762
2548 0 13411 en Malibu's Most Wanted 7.314796
3279 8000000 26306 en Prefontaine 8.717235
3627 5000000 10217 en The Sweet Hereafter 7.673124
4555 0 98568 en Enter Nowhere 3.637857

release_date revenue runtime status title \
2028 28/02/2014 67800064 138.0 Released Son of God
2548 10/04/2003 0 86.0 Released Malibu's Most Wanted
3279 24/01/1997 589304 106.0 Released Prefontaine
3627 14/05/1997 3263585 112.0 Released The Sweet Hereafter
4555 22/10/2011 0 90.0 Released Enter Nowhere

vote_average vote_count
2028 5.9 83
2548 4.7 77
3279 6.7 21
3627 6.8 103
4555 6.5 49

2. 执行一些基本的数据分析来理解数据。

# 识别数据类型
print(f"Output \n*** Datatypes are {movies.dtypes} ")

输出

*** Datatypes are budget int64
id int64
original_language object
original_title object
popularity float64
release_date object
revenue int64
runtime float64
status object
title object
vote_average float64
vote_count int64
dtype: object

2. 现在,如果我们想节省内存使用量,我们可以转换 float64 和 int64 的数据类型。但在转换数据类型之前,我们必须小心谨慎并做好功课。

# Check the maximum numeric value.
print(f"Output \n *** maximum value for Numeric data type - {movies.select_dtypes(exclude=['object']).unstack().max()}")

# what is the max vote count value
print(f" *** Vote count maximum value - {movies[['vote_count']].unstack().max()}")

# what is the max movie runtime value
print(f" *** Movie Id maximum value - {movies[['runtime']].unstack().max()}")

输出

*** maximum value for Numeric data type - 2787965087.0
*** Vote count maximum value - 13752
*** Movie Id maximum value - 338.0

3. 有些列不需要用 64 位表示,可以降到 16 位,所以让我们这样做吧。64 位 int 范围从 -32768 到 +32767。我将对 vote_count 和运行时执行此操作,您可以对需要较少内存存储的列执行此操作。

4. 现在,要确定每年最受欢迎的电影,我们需要按 release_date 分组并获取最大流行度值。典型的 SQL 如下所示。

SELECT movie with max popularity FROM movies GROUP BY movie released year

5. 不幸的是,我们的 release_date 是对象数据类型,有几种方法可以将它们转换为日期时间。我将选择创建一个仅包含年份的新列,以便我可以使用该列进行分组。

movies['year'] = pd.to_datetime(movies['release_date']).dt.year.astype('Int64')
print(f"Output \n ***{movies.sample(n=5)}")

输出

*** budget id original_language original_title popularity \
757 0 87825 en Trouble with the Curve 18.587114
711 58000000 39514 en RED 41.430245
1945 13500000 152742 en La migliore offerta 30.058263
2763 13000000 16406 en Dick 4.742537
4595 350000 764 en The Evil Dead 35.037625

release_date revenue runtime status title \
757 21/09/2012 0 111.0 Released Trouble with the Curve
711 13/10/2010 71664962 111.0 Released RED
1945 1/01/2013 19255873 124.0 Released The Best Offer
2763 4/08/1999 27500000 94.0 Released Dick
4595 15/10/1981 29400000 85.0 Released The Evil Dead

vote_average vote_count year
757 6.6 366 2012
711 6.6 2808 2010
1945 7.7 704 2013
2763 5.7 67 1999
4595 7.3 894 1981

方法 1 - 不使用 Group By

6. 我们只需要 3 列,即电影名称、电影上映年份和受欢迎程度。因此,我们选择这些列,并在年份上使用 sort_values 来查看结果。

print(f"Output \n *** Method 1- Without Using Group By")
movies[["title", "year", "popularity"]].sort_values("year", ascending=True)

输出

*** Without Using Group By



titleyearpopularity
4592Intolerance19163.232447
4661The Big Parade19250.785744
2638Metropolis192732.351527
4594The Broadway Melody19290.968865
4457Pandora's Box19291.824184
............
2109Me Before You201653.161905
3081The Forest201619.865989
2288Fight Valley20161.224105
4255Growing Up Smith20170.710870
4553America Is Still the Place<NA>0.000000

4803 行 × 3 列

8. 现在查看结果,我们还需要对受欢迎程度进行排序,以获得一年中最受欢迎的电影。将 interest 中的列作为列表传递。ascending=False 将导致按降序排列的排序结果。

movies[["title", "year", "popularity"]].sort_values(["year","popularity"], ascending=False)



titleyearpopularity
4255Growing Up Smith20170.710870
788Deadpool2016514.569956
26Captain America: Civil War2016198.372395
10Batman v Superman: Dawn of Justice2016155.790452
64X-Men: Apocalypse2016139.272042
............
4593The Broadway Melody19290.968865
2638Metropolis192732.351527
4660The Big Parade19250.785744
4591Intolerance19163.232447
4552America Is Still the Place<NA>0.000000

4802 行 × 3 列

9. 好了,数据现在排序完美了。所以下一步就是保留每年的第一个值并删除其余值。猜猜怎么做?

我们将使用 .drop_duplicates 方法。

movies[["title", "year", "popularity"]].sort_values(["year","popularity"], ascending=False).drop_duplicates(subset="year")



titleyearpopularity
4255Growing Up Smith20170.710870
788Deadpool2016514.569956
546Minions2015875.581305
95Interstellar2014724.247784
124Frozen2013165.125366
............
4456Pandora's Box19291.824184
2638Metropolis192732.351527
4660The Big Parade19250.785744
4591Intolerance19163.232447
4552America Is Still the Place<NA>0.000000

91 行 × 3 列

方法 2 - 使用 Group By

我们也可以使用 groupby 实现同样的效果。该方法与上面显示的 SQL 非常相似。

print(f"Output \n *** Method 2 - Using Group By")
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)

输出

*** Method 2 - Using Group By



titleyearpopularity
4255Growing Up Smith20170.710870
788Deadpool2016514.569956
546Minions2015875.581305
95Interstellar2014724.247784
124Frozen2013165.125366
............
3804Hell's Angels19308.484123
4457Pandora's Box19291.824184
2638Metropolis192732.351527
4661The Big Parade19250.785744
4592Intolerance19163.232447

90 行 × 3 列


相关文章


有用资源