python - Pandas 中的 sort_values() 方法

标签 python python-3.x sorting pandas

我有以下数据子集,我需要按升序对 Education 列进行排序;从 0 到 17

enter image description here

我尝试了以下代码但没有成功。

suicide_data.sort_index(axis=0, kind='mergesort')

还有...

suicide_data.Education.sort_values()

和...

suicide_data.sort_values('Education')

这是我遇到的错误...

TypeError: '>' not supported between instances of 'float' and 'str'

文档说 str 可以用 sort_values() 方法排序。有谁知道如何按升序对 Education 列进行排序?

最佳答案

看来您的 DataFrame 的 Education 列中必须有混合类型。错误消息告诉您它无法将字符串 与列中的 float 进行比较。假设您想按数字对值进行排序,您可以将它们转换为整数类型,然后 排序。我建议您无论如何都这样做,因为混合类型对于您的 DataFrame 中的任何操作都不会太有用。然后使用 DataFrame.sort_values .

suicide_data['Education'] = suicide_data['Education'].astype('int')
suicide_data.sort_values(by='Education')

还值得指出的是,您的第一次尝试,

suicide_data.sort_index(axis=0, kind='mergesort')

将按您不想要的索引对您的 DataFrame 进行排序,这是您的第二次尝试

suicide_data.Education.sort_values()

只会返回排序后的系列——它们是完全无效的方法。

关于python - Pandas 中的 sort_values() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42477572/

相关文章:

arrays - 如何快速对 Range<Index> 的数组进行排序?

sql - 按降序对列表进行排序的时间复杂度。

将特定列写入输出文件然后在 Excel 中打开时出现 Python CSV 格式问题

Python:使用另一个大字典更新一个大字典

python - 创建嵌套字典的迭代问题

python-3.x - cluster_centers_的排序/索引在KMeans聚类SKlearn中代表什么

c# - 在 C# 中,如何按对象的多个字段对对象集合进行排序?

python - 如何从 Python 修改 SVG 文件的属性?

python - numpy 和 matlab 之间的性能差异

python-3.x - 如何用一个滚动条滚动两个并行的文本小部件?