【问题标题】:sort index using lambda function with string split使用带有字符串拆分的 lambda 函数对索引进行排序
【发布时间】:2022-12-10 17:43:27
【问题描述】:

我有这样的数据框

df_crossplot 

the index is 1A22, 10A22,11A22,2A22,21A22
        value
1A22    10
10A22   12
11A22   11
2A22    15
12A22    21
3A22    25

我喜欢做的是根据 A 之前的数字对索引进行排序,就像这样

        value
1A22    10
2A22    15
3A22    25
10A22   12
11A22   11
12A22    21

我做的是这个有错误


df_crossplot=df_crossplot.sort_index(key=lambda x: float(x.str.split('A')[0]))


TypeError: float() argument must be a string or a number, not 'list'

看起来 lambda 函数中的 x 是一个列表,而不是一系列的每个单独组件,

怎么做?谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    为什么不创建一个新列并按它排序?:

    df['sort_col'] = df.index.str.split('A')[0].astype(int)
    

    【讨论】:

      【解决方案2】:

      natsort如果你想排序索引会很容易工作

      from natsort import natsorted
      print(df.reindex(index=natsorted(df.index)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2018-10-23
        • 1970-01-01
        • 2013-06-29
        相关资源
        最近更新 更多