In this guide, you can learn how to move columns by name to the front in Pandas DataFrame.
There are situations where you might need to move a specific column to the front of the DataFrame:
- for better visibility
- to facilitate further analysis
- to fulfill business requirements
- export purposes
Let's guide you through the process of moving a column by name to the front of a Pandas DataFrame, helping you organize your data more effectively.
For sorting column in DataFrame check: How to Change the Order of Columns in Pandas DataFrame
Data
To illustrate the example let's create simple Pandas DataFrame:
import pandas as pd
# Sample DataFrame
data = {
'id': [1, 2, 3, 4, 5],
'name': ['John', 'Alice', 'Bob', 'Charlie', 'Emma'],
'value': [10, 20, 30, 40, 50],
'category': ['A', 'B', 'C', 'B', 'A']
}
df = pd.DataFrame(data)
df
id | name | value | category | |
---|---|---|---|---|
0 | 1 | John | 10 | A |
1 | 2 | Alice | 20 | B |
2 | 3 | Bob | 30 | C |
3 | 4 | Charlie | 40 | B |
4 | 5 | Emma | 50 | A |
Move Column by pop()
and insert()
To move a specific column to the front of the DataFrame, you can use: Pandas pop()
and insert()
functions:
col = 'category'
column_to_move = df.pop(col)
df.insert(0, col, column_to_move)
Column category will be moved as first column in the DataFrame:
category | id | name | value | |
---|---|---|---|---|
0 | A | 1 | John | 10 |
1 | B | 2 | Alice | 20 |
2 | C | 3 | Bob | 30 |
3 | B | 4 | Charlie | 40 |
4 | A | 5 | Emma | 50 |
Move Column by selecting a list of columns
As an alternative solution we can use Python list comprehension to predefine the column order.
To move single column to front of the DataFrame by using list comprehension we can:
col_to_move = 'category'
df[[col_to_move] + [ col for col in df.columns if col != col_to_move ]]
The result is the same as the on using pop
Move Multiple Columns
To move multiple Pandas columns to the start of the DataFrame we can build a list with the desired column order:
cols_to_move = ['category', 'name']
df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ]]
Now the columns 'category', 'name'
are move at the beginning:
category | name | id | value | |
---|---|---|---|---|
0 | A | John | 1 | 10 |
1 | B | Alice | 2 | 20 |
2 | C | Bob | 3 | 30 |
3 | B | Charlie | 4 | 40 |
4 | A | Emma | 5 | 50 |
Conclusion
Reordering columns in a Pandas DataFrame allows you to organize your data effectively for analysis, sharing and visualization.
Hopefully, now you can easily move a specific columns to the front of the DataFrame.
Resources:
Additional resources on reordering and sorting columns in Pandas: