Python 3.x 通过对另一列中的文本进行优先级排序来分组
我有一个(片段)df: 我想使用Python 3.x 通过对另一列中的文本进行优先级排序来分组,python-3.x,pandas,pandas-groupby,Python 3.x,Pandas,Pandas Groupby,我有一个(片段)df: 我想使用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 S
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,这样就可以通过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
完美的我没有意识到这种可能性,谢谢
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