Built with Tutify.io

    AIStudyLabs

    Pandas - How to Change Position of a Column

    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.

    Key Points –

    <a id="h-create-dataframe"></a>

    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.

    <a id="h-pandas-change-the-position-of-a-column-last-to-the-first"></a>

    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.

    <a id="h-move-the-first-column-to-the-last-in-pandas-dataframe"></a>

    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
    

    <a id="h-move-the-middle-column-to-the-beginning-or-ending-of-the-dataframe"></a>

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

    <a id="h-faq-on-change-position-of-a-column-in-pandas"></a>

    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.

    <a id="h-related-articles"></a>

    Related Articles

    <a id="h-references"></a>

    References