熊猫中的sort_values()方法
我有以下数据子集,我需要Education
按升序对列进行排序;来自0 to 17
。
我尝试了以下代码,但未成功。
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
按升序对列进行排序?
-
看起来
Education
您的DataFrame列中必须具有混合类型。错误消息告诉您,它无法将字符串 与
列中的浮点数进行比较。假设要对值进行数字排序,可以将它们转换为整数类型, 然后再进行
排序。我建议您还是这样做,因为混合类型对于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()
只会返回排序后的序列-它们是完全无效的方法。