【问题标题】:Pandas sort_value not sorting properly [duplicate]Pandas sort_value没有正确排序[重复]
【发布时间】:2020-08-06 22:59:16
【问题描述】:

我在尝试从 0-100 desc 对一列数字进行排序时遇到问题。

df_score = df.sort_values('score', ascending = False)

原始数据框是 df: original df

和排序的df: sorted df

已排序的数据帧已正确排序,但最后两行除外,两者均为 100。它们应该在前两个条目中。

我该如何解决这个问题?谢谢

编辑:该列不是数字形式,这导致了错误。谢谢!

【问题讨论】:

  • 看起来您的分数被排序为字符串而不是数字。
  • 在排序前使用df['score'] = pd.to_numeric(df['score']) 转换为数字,以便解决@JustinEzequiel 提出的问题
  • 啊,这很有意义,现在就这样做了,而且工作正常。谢谢!

标签: python pandas


【解决方案1】:

正如其他人评论的那样,您的分数数据似乎是 str 而不是数字。这将导致它们在某种程度上按字母顺序排序,而不是按值排序。这是一个例子:

import pandas as pd

nums = [2, 10, 5, 3, 1]
strs = [str(i) for i in nums]

df_num = pd.DataFrame(nums, columns = ['score'])
df_str = pd.DataFrame(strs, columns = ['score'])

这两个“看起来”都是这样的:

   score
0      2
1     10
2      5
3      3
4      1

但只有数字会按您的预期排序:

df_num.sort_values('score', ascending = False)

Out[13]: 
   score
1     10
2      5
3      3
0      2
4      1
df_str.sort_values('score', ascending=False)

Out[15]: 
  score
2     5
3     3
0     2
1    10
4     1

正如 ALollz 所说,您可以转换为数字来修复:

df_str['score'] = pd.to_numeric(df_str['score']) #now the sort works

【讨论】:

    【解决方案2】:

    您可能传递的是 STRING 而不是 INT。

    在这种情况下,请检查原始问题中的 cmets,其中另一个用户提供了以下解决方案,可以轻松地将这些值转换为整数:

    df_str['score'] = pd.to_numeric(df_str['score'])

    然后

    df_score = df.sort_values('score', ascending = False)


    假设您打算使用字符串: 在不同语言的许多不同场景中,排序可能很有趣。这里发生的是排序函数将 2 位数分数计算为在 3 位数分数之前排序。例如,如果您有以下分数:

    • 98
    • 999
    • 97
    • 1000
    • 120
    • 998
    • 4
    • 9

    您的排序输出可能如下所示:

    • 9
    • 4
    • 98
    • 97
    • 999
    • 998
    • 120
    • 1000

    您可以查看the documentation for sort_values

    【讨论】:

    • 这是两个答案中更好解释的一个,涵盖了所有可能的问题。这应该是公认的答案。
    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 2014-09-07
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多