0

Edit. I was directed to enter link description here but this can not be the best solution. I am going to use this approach as part of a function later. So I do not know what the column names are in real life examples! I want to make sure WHATEVER the column names are in the future, they are taken care of by reordering their columns. (something like mixedsort/ mixedorder in R)
would you please to do not close a question just because another questions sees similar. maybe a link to that would be nicer as a comment. Thanks.
I have a data frame similar to below.
I want to order the columns based on their names. Names of the columns are alphanumerical.
I am new to Python but as I have learnt so far, sort() is supposed to do so which works when all names are just letters. Any idea how to get to this?


data = {'year': [2014, 2018,2020,2017], 
        'a1': ["toyota", "honda","hyndai","nissan"],
        'a10':["corolla", "civic","accent","sentra"],
        'b10': ["toyota", "honda","hyndai","nissan"],
        'a%':["corolla", "civic","accent","sentra"],
        'a2': ["toyota", "honda","hyndai","nissan"],
        'b':["corolla", "civic","accent","sentra"],
        'b2':["corolla", "civic","accent","sentra"]
       }

# pass column names in the columns parameter 
df = pd.DataFrame(data)
df.sort_index(axis=1) #fails
df.reindex(sorted(df.columns), axis=1) #fails

enter image description here

but I want something like:
enter image description here

Mathica
  • 1,241
  • 1
  • 5
  • 17
  • It looks to me like [natural sorting](/a/68489939) is what you're looking for (which is also demonstrated in the thread you've linked). Why is that not the best solution for your use case? Also why the year column is first in your output? – Henry Ecker Oct 13 '22 at 00:30

1 Answers1

0

Seeing the comment of @Henry, you can use natural sorting here, instead of the lexicographic one available in python. So, this will become

from natsort import natsorted
df = df.loc[:, natsorted(df.columns)]