排序pandas数据帧编号首先是字符串

时间:2018-02-27 14:28:23

标签: python pandas numpy dataframe

我有一个数据框,其中的列包含P123Y8O9数字和字符混合的值,如果我在数据框中对此特定系列应用排序函数,它会将字符串基础排在第一位,然后是第二位,依此类推,我是什么想要首先对所有数字进行排序,例如32456789,然后混合字符串2AJ6JH67

你可以看到,在上面的示例中,数字2 (first digit of 2AJ6JH67)出现在3 (first digit of 32456789)之前,但排序首先要32456789,然后2AJ6JH67

如何以这种方式对数据帧进行排序?

1 个答案:

答案 0 :(得分:0)

一种方法是分别对数字和非数字数据进行排序。

以下是listpd.Series的等效示例。

lst = ['P123Y8O9', '32456789']
lst_sorted = list(map(str, sorted(int(x) for x in lst if x.isdigit()))) + \
             sorted(x for x in lst if not x.isdigit())

# ['32456789', 'P123Y8O9']

s = pd.Series(lst)
s_sorted = pd.Series(list(map(str, sorted(int(x) for x in s if x.isdigit()))) + \
                     sorted(x for x in s if not x.isdigit()))

# 0    32456789
# 1    P123Y8O9
# dtype: object