Sorting is not working for long list of columns for a dataframe in python

Viewed 44

I have a dataframe with a total of 3000 columns having header names as numbers except first column which is a string. All are duplicate columns having similar values. The current order i is:

   First, 0, 1, 2, 3,....3000, 0, 1, 2, 3,....,3000, 0, 1, 2, 3,...,3000, 0, 1, 2, 3,....,3000

I want them to be sorted as follows:

 First, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3,....,3000, 3000, 3000, 3000

All the values are same for these duplicate columns. I tried df = df.sort_index() on axis 1 and similarly, df[sorted(df.columns)] but they give different sorting order and not what i require.

Any help ?

1 Answers

Convert First to index, all another columns to integers, sorting and last convert First to column:

df = df.set_index('First').rename(columns=int).sort_index(axis=1).reset_index()
Related