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:
JavaScript
x
2
1
so = sorted(df.Column1, key=lambda x: (x.isnumeric(),int(x) if x.isnumeric() else x))[::-1]
2
so:
JavaScript
1
2
1
['134', '127', '99', '65', '1', 'Q23', 'N12', 'K9', 'A10']
2
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:
JavaScript
1
2
1
df.set_index('Column1').loc[so, :]
2
JavaScript
1
12
12
1
Column2
2
Column1
3
134 LL
4
127 KK
5
99 QA
6
65 CD
7
1 AA
8
Q23 MM
9
N12 OO
10
K9 MA
11
A10 KL
12
This logic can be applied using sort_values
also. But I ain’t able to do that.