python-3.x - 通过优先考虑另一列中的文本来分组熊猫
问题描述
我有这个(片段)df:
date type
0 200101 SN2
1 200102 SN2
2 200102 LS8
3 200102 SN1
4 200103 SN2
我想pandas
按列对它进行分组,date
列中的值type
需要遵循以下规则:LS8>SN2>SN1。我想出的解决方案是在表示规则的每种类型之前添加一个字母,例如 a_LS8、b_SN2、c_SN1。这样我就可以根据日期和类型对 df 进行排序,然后执行df.groupby(by='date').first()
. 然后删除这个多余的字母。期望的结果将是:
date type
0 200101 SN2
1 200102 LS8
2 200103 SN2
有没有更好的方法来执行该任务?
解决方案
使用 ordered Categorical
,因此可以通过以下方式聚合min
:
df['type'] = pd.Categorical(df['type'], categories=['LS8','SN2','SN1'], ordered=True)
df1 = df.groupby('date', as_index=False)['type'].min()
print (df1)
date type
0 200101 SN2
1 200102 LS8
2 200103 SN2
推荐阅读
- c# - 如何计算 N 维的 Snake Index?
- r - 如何在 R 中跟踪其他环境的值
- bootstrap-4 - 在引导类中使用 HEX 颜色
- ios - 来自 JSON 数据处理程序的无效转换错误?
- php - 在我的网页上,菜单在手机上不起作用。它可以很好地折叠,但是当我单击它时什么也不做
- java - 查找 Checkbox id android 时出错
- php - Windows 10 中的 cron 权限和 xampp 设置
- css - 为什么我的 CSS 链接需要 ?vh=# 才能在我的网站上更新?
- mysql - SQL Join 表 A 上的重复值
- python - 如何在pdfplumber中打开多个文件?