Pandas Groupby返回最大值和其他特定列



假设一个数据帧

import pandas as pd
df = pd.DataFrame({
'Model': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
'Year': [2019, 2020, 2021, 2018, 2019, 2020, 2021],
'Transmission': ['Manual', 'Automatic', 'Automatic', 'Manual', 'Automatic', 'Automatic', 'Manual'],
'EngineSize': [1.4, 2.0, 1.4, 1.5, 2.0, 1.5, 1.5],
'MPG': [55.4, 67.3, 58.9, 52.3, 64.2, 68.9, 83.1]
})
df

并且我想返回每年最高的MPG加上该型号。看起来像这个

Year  MPG   Model
2018 52.3   D
2019 64.2   E
2020 68.9   F
2021 83.1   G

我正在考虑使用groupby,但仍然停留在如何显示Model列上。

您可以使用groupby+idxmax来获得每年最大MPG的索引;然后使用loc过滤:

out = df.loc[df.groupby('Year')['MPG'].idxmax(), ['Year', 'MPG', 'Model']]

输出:

Year   MPG Model
3  2018  52.3     D
4  2019  64.2     E
5  2020  68.9     F
6  2021  83.1     G

我更喜欢@enke的答案。但你可以使用groupbyapplypd.DataFrame.nlargest

df.groupby('Year').apply(pd.DataFrame.nlargest, n=1, columns=['MPG'])
Model  Year Transmission  EngineSize   MPG
Year                                             
2018 3     D  2018       Manual         1.5  52.3
2019 4     E  2019    Automatic         2.0  64.2
2020 5     F  2020    Automatic         1.5  68.9
2021 6     G  2021       Manual         1.5  83.1

最新更新