pandas中的sort_values()方法

2024-10-17 08:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据子集,需要按升序对Education列进行排序;从0 to 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列排序吗?


Tags: to数据代码dataindex排序sort子集
2条回答

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

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

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

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

将根据索引对数据帧进行排序,这是您不需要的,并且您将进行第二次尝试

suicide_data.Education.sort_values()

只会返回已排序的序列-它们是完全无效的方法。

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

相关问题 更多 >