Skip to content
Advertisement

Sorting a table in python with alphabet and numbers

I have the following table:

Column1 Column2
99 QA
65 CD
134 LL
N12 OO
127 KK
Q23 MM
1 AA
A10 KL
K9 MA

I would like to sort the table such that the numbers are sorted in descending order first then the alphabets in descending order. How do I do that? The output should look something like the following:

Column1 Column2
134 LL
127 KK
99 QA
65 CD
1 AA
Q23 MM
N12 OO
K9 MA
A10 KL

Advertisement

Answer

This will do:

so = sorted(df.Column1, key=lambda x: (x.isnumeric(),int(x) if x.isnumeric() else x))[::-1]

so:

['134', '127', '99', '65', '1', 'Q23', 'N12', 'K9', 'A10']

The only thing I need to do is connect it with pandas query. Will update the answer shortly. Right now having trouble with syntax.

Edit:

df.set_index('Column1').loc[so, :]

    Column2
Column1 
134 LL
127 KK
99  QA
65  CD
1   AA
Q23 MM
N12 OO
K9  MA
A10 KL

This logic can be applied using sort_values also. But I ain’t able to do that.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement