Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas sort columns by name

Tags:

python

pandas

I have the following dataframe, where I would like to sort the columns according to the name.

1 | 13_1 | 13_10| 13_2  | 2   | 3
9 |  31  | 2    |  1    | 3   | 4

I am trying to sort the columns in the following way:

1 |  2  | 3    | 13_1  | 13_2  | 13_10
9 |  3  | 4    |  31   |  1    | 2

I've been trying to solve this using df.sort_index(axis=1, inplace=True), however the result turns out to be the same as my initial dataframe. I.e:

1 | 13_1 | 13_10| 13_2  | 2   | 3
9 |  31  | 2    |  1    | 3   | 4

It seems it recognizes 13_1 as 1.31 and not as 13.1. Furthermore, I tried a conversion of the column names from string to float. However, this turns out to treat 13_1 and 13_10 both as 13.1 giving me duplicate column names.

like image 629
AaronDT Avatar asked Dec 04 '22 18:12

AaronDT


1 Answers

natsort

from natsort import natsorted

df = df.reindex(natsorted(df.columns), axis=1)

#   1  2  3  13_1  13_2  13_10
#0  9  3  4    31     1      2
like image 73
ALollz Avatar answered Dec 25 '22 15:12

ALollz