(Small story) Sort columns by column name with one liner in pandas.DataFrame

This is a quick one-liner method when you want to sort columns by "column name" in pandas DataFrame.

When there is a DataFrame like

df = pd.DataFrame({4:[1,2,3], 2: [1,2,3], 1:[1,2,3], 3: [1,2,3]})

image.png

You can do it with the code below.

df.T.sort_index().T

image.png

You can do the same with alphabetic column names.

df = pd.DataFrame({'d':[1,2,3], 'b': [1,2,3], 'a':[1,2,3], 'c': [1,2,3]})
df.T.sort_index().T

image.png

Hiragana also went well.

df = pd.DataFrame({'e':[1,2,3], 'I': [1,2,3], 'Ah':[1,2,3], 'U': [1,2,3]})
df.T.sort_index().T

image.png

Kanji was not good. (Something is regrettable.)

df = pd.DataFrame({'four':[1,2,3], 'two': [1,2,3], 'one':[1,2,3], 'three': [1,2,3]})
df.T.sort_index().T

image.png

As mentioned above, it was a small story that could be used somewhere.

Recommended Posts

(Small story) Sort columns by column name with one liner in pandas.DataFrame
One liner webServer (with CGI) in python
[Python] Sort spreadsheet worksheets by sheet name with gspread
One liner in Python
[Small story] [Python] Replace strings in 2D arrays with numbers
Sort by date in python