Pandas provide reindex()
, insert()
, and select by columns to change the position of a DataFrame column. In this article, let’s see how to change the position of the last column to the first, move the first column to the end, or get the column from the middle to the first or last with examples.
Key Points –
- You can change the position of a column by reordering the columns in a DataFrame using column indexing, creating a new column order.
- The
insert()
method allows you to move a column to a specific position by specifying the index location and column name. - A common approach to change the column’s position is to use
pop()
to remove the column, followed byinsert()
to place it at a desired index. - You can directly manipulate the column names using the
df.columns
attribute to reorder them by reassigning a list of column names in the desired order. - The
reindex()
method can also be used to reorder columns by specifying a new order in thecolumns
parameter. - Many column repositioning operations, such as using
insert()
, modify the DataFrame in place, while others (like reordering withdf.columns
) may return a new DataFrame.
Create DataFrame
Let’s create a DataFrame with the columns of 'Courses'
, 'Fee'
, 'Duration'
, and 'Discount'.
# Create DataFrame
import pandas as pd
import numpy as np
technologies= {
'Courses':["Spark","PySpark"],
'Fee' :[22000.30,25000.40],
'Duration':['30days','50days'],
'Discount':[1000.10,2300.15]
}
df = pd.DataFrame(technologies)
print("Create DataFrame:\n", df)
Yields below output.
Pandas Change the Position of a Column (Last to the First)
You can change the position of a Pandas column using the df.reindex() function by changing the order of Pandas column’s position in the desired order. For example, first, specify the order of the column’s position and pass it into the reindex() function, it will change the column’s position with the desired order.
# Move last Column to First Column
new_cols = ["Discount","Courses","Fee","Duration"]
df = df[new_cols]
print("After changing the position of the columns:\n", df)
# Or
df = df.reindex(columns=new_cols)
print("After changing the position of the columns:\n", df)
Yields below output. This is not feasible if you have 100’s of columns.
Alternatively, you can also try selecting columns by indexes.
# Move last column to the first
df = pd.DataFrame(technologies)
temp_cols=df.columns.tolist()
new_cols=temp_cols[-1:] + temp_cols[:-1]
df=df[new_cols]
print("After changing the position of the columns:\n", df)
Pandas also provide a DataFrame.insert() method to insert a column into DataFrame at the specified location. To use this, you need to know the column names you want to move.
# If you know the column name
df = pd.DataFrame(technologies)
col = df.pop("Discount")
df = df.insert(0, col.name, col)
print("After changing the position of the columns:\n", df)
Output is the same as the above.
Move the First Column to the Last in Pandas DataFrame
Now let’s see how to move the first column to the last position in Pandas DataFrame.
# Move first column to the Last
df = pd.DataFrame(technologies)
temp_cols=df.columns.tolist()
new_cols=temp_cols[1:] + temp_cols[0:1]
df=df[new_cols]
print("After changing the position of the columns:\n", df)
Yields below output.
# Output:
# After changing the position of the columns:
Fee Duration Discount Courses
0 22000.3 30days 1000.10 Spark
1 25000.4 50days 2300.15 PySpark
Move the Middle Column to the beginning or Ending of the DataFrame
Moving first to last and last to first is simple, now let’s see moving the middle column to the first position of the DataFrame.
# Move Middle column to the Begining
df = pd.DataFrame(technologies)
temp_cols=df.columns.tolist()
index=df.columns.get_loc("Duration")
new_cols=temp_cols[index:index+1] + temp_cols[0:index] + temp_cols[index+1:]
df=df[new_cols]
print("After changing the position of the columns\n:", df)
Yields below output.
# Output:
# After changing the position of the columns:
Duration Courses Fee Discount
0 30days Spark 22000.3 1000.10
1 50days PySpark 25000.4 2300.15
I will leave it to you to explore moving the middle column to the last position.
Happy Learning !!
FAQ on Change Position of a Column in Pandas
To move a column to the first position in a Pandas DataFrame, you can reorder the columns by explicitly specifying the desired column order.
To move a column to the last position in a Pandas DataFrame, you can reorder the columns by explicitly specifying the desired order.
You can move a column to a specific position (e.g., the 3rd position) in a Pandas DataFrame using the pop()
and insert()
methods.
You can dynamically rearrange multiple columns to desired positions in a Pandas DataFrame by defining a new column order. This approach is highly flexible and can handle any number of columns.
These operations are memory-efficient and safe for large DataFrames, but always verify the operation if the DataFrame is very large.
Related Articles
- Pandas Get Last Row from DataFrame?
- Pandas Groupby Aggregate Explained
- Get First N Rows of Pandas DataFrame
- Pandas How to Rename DataFrame Columns?
- Pandas How to Add a new Column to DataFrame?
- Pandas How to Drop single or multiple columns?
- Pandas Get Column Name by Index or Position
Remove `df = ` in
“`
# if you know the column name
df = pd.DataFrame(technologies)
col = df.pop(“Discount”)
df = df.insert(0, col.name, col)
print(df)
“`