• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:7 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

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

1. 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)

Output is the same as the above.

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.

2. 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

3. 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 !!

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