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.
natsortfrom 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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With