Reordering columns in Pandas can be a useful technique when you want to rearrange the column order of a DataFrame. This can be particularly helpful if you want to rearrange the columns to match a specific order, or if you want to move a column to a different position in the DataFrame.
There are several ways to reorder columns in Pandas, and in this article, we will explore some of the most common methods.
Table of Contents
Method 1: Using the reindex
method
One way to reorder columns in Pandas is to use the reindex
method. This method allows you to specify a list of column labels, and the DataFrame will be reordered to match the order of the labels in the list.
Here’s an example of how to use the reindex
method to reorder the columns of a DataFrame:
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# Print the original DataFrame
print(df)
# Reorder the columns using the reindex method
df = df.reindex(columns=['C', 'A', 'B'])
# Print the reordered DataFrame
print(df)
Code language: PHP (php)
The output of this code will be:
A B C 0 1 4 7 1 2 5 8 2 3 6 9 C A B 0 7 1 4 1 8 2 5 2 9 3 6
Method 2: Using the columns
attribute
Another way to reorder columns in Pandas is to use the columns
attribute. This attribute allows you to assign a list of column labels to the DataFrame, and the DataFrame will be reordered to match the order of the labels in the list.
Here’s an example of how to use the columns
attribute to reorder the columns of a DataFrame:
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# Print the original DataFrame
print(df)
# Reorder the columns using the columns attribute
df.columns = ['C', 'A', 'B']
# Print the reordered DataFrame
print(df)
Code language: PHP (php)
The output of this code will be the same as in the previous example:
A B C 0 1 4 7 1 2 5 8 2 3 6 9 C A B 0 7 1 4 1 8 2 5 2 9 3 6
Method 3: Using the loc
indexer
A third way to reorder columns in Pandas is to use the loc
indexer. This indexer allows you to specify a list of column labels, and the DataFrame will be
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# Print the original DataFrame
print(df)
# Reorder the columns using the loc indexer
df = df.loc[:, ['C', 'A', 'B']]
# Print the reordered DataFrame
print(df)
Code language: PHP (php)
The output of this code will be the same as in the previous examples:
A B C 0 1 4 7 1 2 5 8 2 3 6 9 C A B 0 7 1 4 1 8 2 5 2 9 3 6
As you can see, the loc
indexer allows you to select the columns of a DataFrame by label, and you can specify the order of the columns by passing a list of labels to the indexer.