python - 使用 Pandas 对数据框进行排序。保持列完好无损

标签 python pandas sorting dataframe

如下图所示,我想按字母顺序按类型 对聊天进行排序。但是,我不想弄乱每个 Chat name[Date , User_id] 的顺序。鉴于我在左侧有输入数据框,我应该怎么做? (在 python 中使用 Pandas)

enter image description here

最佳答案

您想使用 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/

相关文章:

objective-c - 如何使用 sortedArrayUsingDescriptors 对 NSMutableArray 进行排序?

Python-填充未使用的日期

python - 使用 dictread 时出现空键

python - 删除数组中的特定列

python - 在 Pandas 中按特定月份和日期进行切片

c++ - 指向另一个 vector 的对象的指针 vector - 初始化和排序

python - Pandas 数据框与自身的笛卡尔积

python - 将从 pd.df ['x' ].mode()[0] 获得的值连接到字典中的键

python - 如何使用 pandas 中的 DataFrame.hist(by=) 在特定轴上绘制

java - 这是将 Java 映射转换为 native Clojure 映射以进行排序的最佳方法吗?