pandas中的sort_values()方法

6
我有以下数据子集,需要将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'

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

1
你想按照“education”列对整个DataFrame进行排序,还是只想重新分配已排序的列(这似乎不太合理)? - miradulo
我想按照教育列的升序对整个数据框进行排序。 - redeemefy
2个回答

19
看起来你的DataFrame的Education列中混杂了不同的类型。错误信息告诉你它无法比较该列中的字符串浮点数。假设你想按数字排序,你可以将它们转换为整数类型,然后排序。我建议你这样做,因为混合类型对于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()

只返回已排序的系列 - 这些完全无效。

3
suicide_data['Education'].sort_values('Education', ascending = 'True')

3
虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - Maximilian Peters

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