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