Rearrange Columns of pandas DataFrame in Python (2 Examples)

In this Python tutorial you’ll learn how to sort the columns of a pandas DataFrame.

Preparing the Examples

import pandas as pd                                # Load pandas library
my_df = pd.DataFrame({'C':[5, 1, 5, 1, 2, 8, 2],  # Construct example DataFrame in Python
                      'A':['b', 'x', 'a', 'a', 'c', 'x', 'b'],
                      'B':['a', 'a', 'c', 's', 'a', 'f', 'c']})
print(my_df)                                      # Display example DataFrame in console
#    C  A  B
# 0  5  b  a
# 1  1  x  a
# 2  5  a  c
# 3  1  a  s
# 4  2  c  a
# 5  8  x  f
# 6  2  b  c

Example 1: Using sort_index() Function to Sort Alphabetically

print(my_df.sort_index(axis = 1))                 # Apply sort_index function
#    A  B  C
# 0  b  a  5
# 1  x  a  1
# 2  a  c  5
# 3  a  s  1
# 4  c  a  2
# 5  x  f  8
# 6  b  c  2

Example 2: Using List of Column Names to Sort Manually

print(my_df[['B', 'A', 'C']])                     # Specify list to sort data
#    B  A  C
# 0  a  b  5
# 1  a  x  1
# 2  c  a  5
# 3  s  a  1
# 4  a  c  2
# 5  f  x  8
# 6  c  b  2

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top