0
votes

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
2
assume K9 and A10 are sorted incorrectly in your example? - Umar.H
Are the 134,... actual numbers or strings? - Quang Hoang
134,... are numbers - Suchi18

2 Answers

1
votes

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.

1
votes

you need two sorts, one on the integers then one on the integers with letters.

we can concat the result and pass the index into your main df.

idx = pd.concat([
            df['Column1'].loc[~pd.to_numeric(df['Column1'],errors='coerce').isna()].astype(int).sort_values(ascending=False),
            df['Column1'].loc[pd.to_numeric(df['Column1'],errors='coerce').isna()].str.replace('\d+','').sort_values(ascending=False)]).index


print(df.loc[idx])



  Column1 Column2
2     134      LL
4     127      KK
0      99      QA
1      65      CD
6       1      AA
5     Q23      MM
3     N12      OO
8      K9      MA
7     A10      KL