Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why is my column index not sorted properly?

I want to sort such a dataframe(df) and I want to sort the columns by index on ascending order so I type in:

df_sorted=df.sort_index(axis=1,level=int)

however it returns me the order like this… isn’t the column should be ordered in int like 1,2,3,….115?

1    10  100  101    102    103  104 ...   94  95  96  97  98  99  Unnamed: 0
0    0   0    0    0    0    0    0  ...   0   0   0   0   0   0           1
1    0   0    0    0    0    0    0  ...   0   0   0   0   0   0           2
2    0   0    0    0    0    0    0  ...   0   0   0   0   0   0           3
3    0   0    0    0    0    0    0  ...   0   0   0   0   0   0           4
4    0   0    0    0    0    0    0  ...   0   0   0   0   0   0           5
..  ..  ..  ...  ...  ...  ...  ...  ...  ..  ..  ..  ..  ..  ..         ...
111  0   0    0    0    0    0    0  ...   0   0   0   0   0   0         110
112  0   0    0    0    0    0    0  ...   0   0   0   0   0   0         111
113  0   0    0    0    0    0    0  ...   0   0   0   0   0   0         112
114  0   0    0    0    0    0    0  ...   0   0   0   0   0   0         113
115  0   0    0    0    0    0    0  ...   0   0   0   0   0   0         114

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Check your index type, it should be object

df.columns.dtype
dtype('O')

We need to convert to numeric

out = df.iloc[:,pd.to_numeric(df.columns,errors='coerce').argsort()]

Or

df.columns = df.columns.astype(object)
df = df.sort_index(axis=1)

With another package

import natsort as ns 

out = df.iloc[:,ns.index_natsorted(df.columns)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading