Python pandas按组排序而不是内部排序(重新排列分组行但保持groupby之前的原始行顺序)

3
我希望能够根据一列对行进行分组排序(在我的示例中,“Group”是要分组并按顺序排序的列)。我无法按索引排序,因为索引由于先前的操作而有意被打乱了顺序。
df = pd.DataFrame({
    'Group':[5,5,5,9,9,777,777,1,2,2],  
    'V1':['a','b','a',3,6,1,None,10,3,None], 
    'V2':['blah','blah','blah','dog','cat','cat','na','first','last','nada'],
    'V3':[1,2,3,4,5,5,4,3,2,1,]
})

original df

并希望它看起来像这样:

desired result


我已经尝试了各种方法,比如

df.groupby(['Group'])['Group']).aggregate({'min grp':'min'}).sort_values(by=['min grp'], ascending=True)

如果有帮助的话,原始的 df 是通过 pd.concat(list-of-dataframes) 创建的,当我之后按照 Group 对它们进行排序时,它也会根据索引对 Group 内的行进行排序,这对于我的特定问题不起作用。
2个回答

3

您需要使用sort_values并使用选项kind='mergesort'。参考Pandas文档:

kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’
      Choice of sorting algorithm. See also ndarray.np.sort for more
      information. mergesort is the only stable algorithm. For DataFrames,
      this option is only applied when sorting on a single column or label.

当两个具有相同键的元素按照输入顺序出现时,称排序算法为稳定排序。一些稳定排序算法包括:插入排序、归并排序、冒泡排序、Tim排序、计数排序

df = df.sort_values('Group', kind='mergesort')

如果您调用sort_values时没有指定kind,它将默认为“quicksort”,而quicksort是不稳定的。


0
如果我正确理解了您的问题,您不想进行分组,而是按照您的列Group的值进行排序。您可以使用pandas.sort_values()来实现。
df.sort_values('Group', inplace=True)

pandas 不会默认使用稳定排序。 - C. Yduqoli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接