如下图所示,我想按字母顺序按类型
对聊天进行排序。但是,我不想弄乱每个 Chat name
中 [Date , User_id]
的顺序。鉴于我在左侧有输入数据框,我应该怎么做? (在 python 中使用 Pandas)
最佳答案
您想使用 a stable sorting algorithm 对值进行排序这是合并排序:
df.sort_values(by='Type', kind='mergesort')
来自链接的答案:
A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted.
来自 pandas docs :
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.
更新:正如@ALollz 正确指出的那样,最好先将所有值转换为小写,然后再进行排序(即,否则“Bird”将放在“aligator”之前结果):
df['temp'] = df['Type'].str.lower()
df = df.sort_values(by='temp', kind='mergesort')
df = df.drop('temp', axis=1)
关于python - 使用 Pandas 对数据框进行排序。保持列完好无损,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52973106/