Built with Tutify.io

    AIStudyLabs

    How to Change Position of a Column in Polars

    How to Change Position of a Column in Polars

    In Polars, you can change the position of a column in a DataFrame using the select() method by reordering the columns explicitly. In this article, I will explain how to move the last column to the first, shift the first column to the end, or reposition a middle column to either the beginning or the end with examples.

    Key Points–

    <a id="h-usage-of-change-position-of-a-column-in-polars"></a>

    Usage of Change Position of a Column in Polars

    You can change the order of columns in a Polars DataFrame using the select() method. Simply specify the columns in the desired order.

    To run some examples of how to change position of a column in polars, let’s create a Polars DataFrame.

    
    import polars as pl
    
    technologies= {
        'Courses':["Spark","PySpark","Hadoop", "Python"],
        'Fee' :[22000,25000,23000, 24000],
        'Duration':['30days','50days','60days', '45days'],
        'Discount':[1000,2300,2000, 1200]
              }
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To reorder columns in a Polars DataFrame using select() method, you can specify the desired column order.

    
    # Reorder columns: Discount first, then Courses, Fee, Duration
    df2 = df.select(["Discount", "Courses", "Fee", "Duration"])
    print("Reordered DataFrame:\n", df2)
    

    Here,

    <a id="h-move-single-column-to-front"></a>

    Move Single Column to Front

    To move a single column to the front (first position) in a Polars DataFrame, you can use select() along with pl.col() and pl.all() functions.

    
    # Move "Discount" to the front
    df2 = df.select(["Discount"] + [col for col in df.columns if col != "Discount"])
    print("Reordered DataFrame (Courses moved to last):\n", df2)
    
    # Move "Duration" to the front
    df2 = df.select(
        pl.col("Duration"), 
        pl.all().exclude("Duration"))
    print("Reordered DataFrame (Courses moved to last):\n", df2)
    
    # Output:
    # Reordered DataFrame (Courses moved to last):
    # shape: (4, 4)
    ┌──────────┬─────────┬───────┬──────────┐
    │ Discount ┆ Courses ┆ Fee   ┆ Duration │
    │ ---      ┆ ---     ┆ ---   ┆ ---      │
    │ i64      ┆ str     ┆ i64   ┆ str      │
    ╞══════════╪═════════╪═══════╪══════════╡
    │ 1000     ┆ Spark   ┆ 22000 ┆ 30days   │
    │ 2300     ┆ PySpark ┆ 25000 ┆ 50days   │
    │ 2000     ┆ Hadoop  ┆ 23000 ┆ 60days   │
    │ 1200     ┆ Python  ┆ 24000 ┆ 45days   │
    └──────────┴─────────┴───────┴──────────┘
    

    Here,

    <a id="h-move-column-to-specific-position"></a>

    Move Column to Specific Position

    To move a column to a specific position (not just the front) in a Polars DataFrame, you can use select() with a custom column order.

    
    def move_column(df: pl.DataFrame, col: str, pos: int) -> pl.DataFrame:
        cols = df.columns
        if col not in cols:
            raise ValueError(f"Column '{col}' not found!")
        new_order = cols[:pos] + [col] + [c for c in cols if c != col and c not in cols[:pos]]
        return df.select(new_order)
    
    # Move "Duration" to index 0 (first position)
    df2 = move_column(df, "Duration", 0)
    print("After changing the position of the columns:\n", df2)
    
    # Output:
    # After changing the position of the columns:
    # shape: (4, 4)
    ┌──────────┬─────────┬───────┬──────────┐
    │ Duration ┆ Courses ┆ Fee   ┆ Discount │
    │ ---      ┆ ---     ┆ ---   ┆ ---      │
    │ str      ┆ str     ┆ i64   ┆ i64      │
    ╞══════════╪═════════╪═══════╪══════════╡
    │ 30days   ┆ Spark   ┆ 22000 ┆ 1000     │
    │ 50days   ┆ PySpark ┆ 25000 ┆ 2300     │
    │ 60days   ┆ Hadoop  ┆ 23000 ┆ 2000     │
    │ 45days   ┆ Python  ┆ 24000 ┆ 1200     │
    └──────────┴─────────┴───────┴──────────┘
    

    <a id="h-move-last-column-to-first-position"></a>

    Move Last Column to First Position

    You can move a column from the last position to the first in Polars using the select() method. Now let’s see how to move the last column to the first position in Polars DataFrame.

    
    # Move 'Discount' (last column) to the first position
    columns = df.columns
    new_order = [columns[-1]] + columns[:-1]  
    df2 = df.select(new_order)
    print("Reordered DataFrame:\n", df2)
    
    # Output:
    # Reordered DataFrame:
    # shape: (4, 4)
    ┌──────────┬─────────┬───────┬──────────┐
    │ Discount ┆ Courses ┆ Fee   ┆ Duration │
    │ ---      ┆ ---     ┆ ---   ┆ ---      │
    │ i64      ┆ str     ┆ i64   ┆ str      │
    ╞══════════╪═════════╪═══════╪══════════╡
    │ 1000     ┆ Spark   ┆ 22000 ┆ 30days   │
    │ 2300     ┆ PySpark ┆ 25000 ┆ 50days   │
    │ 2000     ┆ Hadoop  ┆ 23000 ┆ 60days   │
    │ 1200     ┆ Python  ┆ 24000 ┆ 45days   │
    └──────────┴─────────┴───────┴──────────┘
    

    Here,

    <a id="h-move-multiple-columns-by-pattern"></a>

    Move Multiple Columns by Pattern

    You can rearrange multiple columns based on a pattern dynamically. This is useful when you need to group specific columns together or reorder them based on a naming convention.

    
    # Define a pattern-based column selection
    pattern = ["Fee", "Discount"]  # Move these to the front
    
    # Separate columns matching the pattern and the rest
    matching_cols = [col for col in df.columns if any(p in col for p in pattern)]
    remaining_cols = [col for col in df.columns if col not in matching_cols]
    
    # New column order
    new_order = matching_cols + remaining_cols
    
    # Reorder DataFrame
    df2 = df.select(new_order)
    print("Reordered DataFrame Matching columns moved to the front:\n", df2)
    
    # Output:
    # Reordered DataFrame Matching columns moved to the front:
     shape: (4, 4)
    ┌───────┬──────────┬─────────┬──────────┐
    │ Fee   ┆ Discount ┆ Courses ┆ Duration │
    │ ---   ┆ ---      ┆ ---     ┆ ---      │
    │ i64   ┆ i64      ┆ str     ┆ str      │
    ╞═══════╪══════════╪═════════╪══════════╡
    │ 22000 ┆ 1000     ┆ Spark   ┆ 30days   │
    │ 25000 ┆ 2300     ┆ PySpark ┆ 50days   │
    │ 23000 ┆ 2000     ┆ Hadoop  ┆ 60days   │
    │ 24000 ┆ 1200     ┆ Python  ┆ 45days   │
    └───────┴──────────┴─────────┴──────────┘
    

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

    Conclusion

    In conclusion, changing the position of columns in Polars is a powerful yet simple operation that improves data readability, consistency, and processing efficiency. By using the select() method, you can dynamically reposition single or multiple columns to the beginning, end, or any specific location. This is especially beneficial for tasks such as data preprocessing, reporting, merging, exporting, and visualization.

    Happy Learning !!

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

    Related Articles

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

    References