How can I sort columns in a Pandas dataframe by their name?

Pandas is a popular Python library used for data manipulation and analysis. One of its key features is the ability to sort columns in a dataframe by their name. This allows for easier organization and analysis of data. To sort columns in a Pandas dataframe, the user can use the “sort_values” function and specify the desired column names. The dataframe will then be rearranged in alphabetical order based on the specified columns. This feature is particularly useful for large datasets with numerous columns, making it easier to locate and analyze specific data. By using this functionality, users can efficiently manage and manipulate their data in a systematic manner.

Pandas: Sort Columns by Name


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

df = 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

x