【问题标题】:Pandas sort column with numerical string带有数字字符串的 Pandas 排序列
【发布时间】:2021-12-01 09:03:41
【问题描述】:

我在下面有一个数据框:

col1

Numb10
Numb11
Numb12
Numb7
Numb8

如何按数字顺序排序:

col1

Numb7
Numb8
Numb10
Numb11
Numb12

我试过了,但得到了错误TypeError: cannot convert the series to <class 'int'>

df.sort_values(by = "col1", key = (lambda x: int(x[4:])))

更新col1中缺少一个

【问题讨论】:

    标签: python pandas sorting


    【解决方案1】:

    sort_values 中的key 将 Series 作为参数而不是单个元素。来自文档:

    在排序前将键函数应用于值。这类似于内置 sorted() 函数中的 key 参数,显着的区别是这个 key 函数应该被矢量化。它应该期望一个系列并返回一个与输入具有相同形状的系列。它将独立应用于 by 中的每一列。

    在您的情况下,您可以使用.strastype 进行切片和类型转换:

    df.sort_values(by='col1', key=lambda s: s.str[4:].astype(int))
         col1
    3   Numb7
    4   Numb8
    0  Numb10
    1  Numb11
    2  Numb12
    

    【讨论】:

      【解决方案2】:

      您的x[4:] 可能并不总是整数。您可以使用验证

      # convert to numerical values, float, not integers
      extracted_nums = pd.to_numeric(df['col1'].str[4:], errors='coerce')
      
      # check for invalid values
      # if not `0` means you have something that are not numerical
      print(extracted_nums.isna().any())
      
      # sort by values
      df.loc[extracted_nums.sort_values().index]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 2016-01-23
        • 2012-08-19
        • 1970-01-01
        相关资源
        最近更新 更多