首页 > 解决方案 > 在系列中查找“最小”自定义类别

问题描述

使用 pandas DataFrames,我希望能够按一个 ID 进行分组,然后获得该 ID 的最高“排名”,如下所示:

df1.groupby(['Name'],as_index=False)['Placement'].agg(getHighestPlacement)

例如,

Name   Placement
Joe    First Place
Joe    Second Place
Joe    Second Place
Jill   Third Place    
Jill   Second Place
Jill   Second Place

我想回来

Name    Placement
Joe     First Place
Jill    Second Place

我正在考虑编写一个函数来完成它,也许按顺序定义一个放置列表,然后尝试获取最小索引并将该包传递到列表中以返回该索引处的元素?我需要这个函数来接收一个系列并返回一个字符串。最干净的方法是什么?我对python还是很陌生。

标签: pythonpandasfunction

解决方案


您可以将Placement列转换为Categorical,然后对其进行排序和分组:

d = {'Name':['Joe', 'Joe', 'Joe', 'Jill', 'Jill', 'Jill'],
     'Placement': ['First Place', 'Second Place', 'Second Place', 'Third Place', 'Second Place', 'Second Place']}

df = pd.DataFrame(d)

# convert Placement to Categorical
df['Placement'] = pd.Categorical(df['Placement'], categories=['First Place', 'Second Place', 'Third Place'], ordered=True)
print(df.loc[df.sort_values('Placement').groupby('Name')['Placement'].head(1).index])

印刷:

   Name     Placement
0   Joe   First Place
4  Jill  Second Place

推荐阅读