Pandas: How to Sort Columns by Name


You can use the following syntax to quickly sort a pandas DataFrame by column names:

df[['column1', 'column4', 'column3', 'column2']]

The following examples show how to use this syntax in practice.

Example 1: Sort Pandas DataFrame by Column Names

The following code shows how to sort a pandas DataFrame by column names:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12],
                   'steals': [2, 3, 3, 2, 5, 3, 2, 1]})

#list column names
list(df)

['points', 'assists', 'rebounds', 'steals']

#sort columns by names
df = df[['steals', 'assists', 'rebounds', 'points']]

df

	steals	assists	rebounds  points
0	2	5	11	  25
1	3	7	8	  12
2	3	7	10	  15
3	2	9	6	  14
4	5	12	6	  19
5	3	9	5	  23
6	2	9	9	  25
7	1	4	12	  29

Example 2: Sort Pandas DataFrame by List

The following code shows how to sort a pandas DataFrame by a list of names:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12],
                   'steals': [2, 3, 3, 2, 5, 3, 2, 1]})

#define list of column names
name_order = ['steals', 'assists', 'rebounds', 'points']

#sort columns by list
df = df[name_order]

df

	steals	assists	rebounds  points
0	2	5	11	  25
1	3	7	8	  12
2	3	7	10	  15
3	2	9	6	  14
4	5	12	6	  19
5	3	9	5	  23
6	2	9	9	  25
7	1	4	12	  29

Example 3: Sort Pandas DataFrame Alphabetically

The following code shows how to sort a pandas DataFrame alphabetically:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12],
                   'steals': [2, 3, 3, 2, 5, 3, 2, 1]})

#sort columns alphabetically
df = df[sorted(df.columns)]

df

	assists	points	rebounds  steals
0	5	25	11	  2
1	7	12	8	  3
2	7	15	10	  3
3	9	14	6	  2
4	12	19	6	  5
5	9	23	5	  3
6	9	25	9	  2
7	4	29	12	  1

Additional Resources

How to Sort a Pandas DataFrame by Date
How to Find Unique Values in a Pandas Column

Leave a Reply

Your email address will not be published. Required fields are marked *