python - 在系列中查找“最小”自定义类别
问题描述
使用 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还是很陌生。
解决方案
您可以将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
推荐阅读
- android - 尝试将图像插入到 sqlite 数据库 API 21
- c++ - 为什么在创建矩阵时使用“** int A”而不是“int A”(c++)
- c - 我收到错误“未指定与字符串文字的比较结果(改用 strncmp)”
- python - 如何处理此类列表输入?
- javascript - 向 Riot API 发送 ajax 请求时遇到问题
- flutter - 如何在应用启动时初始化变量?
- sql - sql关系表
- javascript - 为什么 d3 在我的 React 应用程序的 Chrome 控制台中未定义?
- c# - 如何在引用 .Net 标准库项目的 Xamarin Android 应用程序中进行调试和错误处理
- c# - .NET-Core 3 MVC 控制器 Url.Action 返回 null