I am trying to sort the columns of a .csv file. These are the names and 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 is as follows:
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 column order:
'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 realized that I need to pass a function to a sorted function to indicate how I want to sort it, but I can’t find a function that would do this.
Any input is welcome!