• Post author:
  • Post category:Pandas
  • Post last modified:December 1, 2024
  • Reading time:11 mins read
You are currently viewing Pandas – How to Change Position of a Column

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.

Advertisements

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 by insert() 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 the columns parameter.
  • Many column repositioning operations, such as using insert(), modify the DataFrame in place, while others (like reordering with df.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 position column

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.

pandas change position column

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

How do I move a column to the first position?

To move a column to the first position in a Pandas DataFrame, you can reorder the columns by explicitly specifying the desired column order.

How do I move a column to the last position?

To move a column to the last position in a Pandas DataFrame, you can reorder the columns by explicitly specifying the desired order.

Can I move a column to a specific position (e.g., 3rd position)?

You can move a column to a specific position (e.g., the 3rd position) in a Pandas DataFrame using the pop() and insert() methods.

Is there a way to do this dynamically for multiple columns?

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.

Can I use this method with large DataFrames?

These operations are memory-efficient and safe for large DataFrames, but always verify the operation if the DataFrame is very large.

References

Leave a Reply

This Post Has One Comment

  1. Anonymous

    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)
    “`