gpt4 book ai didi

python - Pandas 中的 sort_values() 方法

转载 作者:太空狗 更新时间:2023-10-30 00:23:59 35 4
gpt4 key购买 nike

我有以下数据子集,我需要按升序对 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com