首页 > 解决方案 > 通过优先考虑另一列中的文本来分组熊猫

问题描述

我有这个(片段)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

有没有更好的方法来执行该任务?

标签: python-3.xpandaspandas-groupby

解决方案


使用 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

推荐阅读