I'm trying to sort the columns of a .csv file. These are the names and the order of the columns:
'Unnamed: 0', 'Unnamed: 1',
'25Mg BLK', '25Mg 1', '25Mg 2',
'44Ca BLK', '44Ca 1', '44Ca 2',
'137Ba BLK', '137Ba 1', '137Ba 2',
'25Mg 3', '25Mg 4', '25Mg 5',
'44Ca 3', '44Ca 4', 44Ca 5',
'137Ba 3', '137Ba 4', '137Ba 5',
This is the order I would like to have:
'Unnamed: 0', 'Unnamed: 1',
'25Mg BLK', '25Mg 1', '25Mg 2', '25Mg 3', '25Mg 4', '25Mg 5',
'44Ca BLK', '44Ca 1', '44Ca 2', '44Ca 3', '44Ca 4', 44Ca 5',
'137Ba BLK', '137Ba 1', '137Ba 2', '137Ba 3', '137Ba 4', '137Ba 5',
Currently my code looks like this:
import pandas as pd
df = pd.read_csv("real_data.csv", header=2)
df2 = df.reindex_axis(sorted(df.columns), axis=1)
print(df2)
df2.to_csv("sorted.csv")
With my current code I get the following result for the order of the columns:
'137Ba 1', '137Ba 2', '137Ba 3', '137Ba 4', '137Ba 5', '137Ba BLK',
'25Mg 1', '25Mg 2', '25Mg 3', '25Mg 4', '25Mg 5', '25Mg BLK',
'44Ca 1', '44Ca 2', '44Ca 3', '44Ca 4', '44Ca 5', '44Ca BLK'
So I already figured out that I have to pass a function to the sorted function to specify how I want it to sort it, but I can't figure out a function which would do that.
Any input is highly appreciated!