Built with Tutify.io

    AIStudyLabs

    Polars DataFrame.rename() Method

    Polars DataFrame.rename() Method

    In Polars, the rename() method is used to rename the column names of a DataFrame by providing a mapping of the current column names to the new names. This method requires a dictionary where the keys represent the current column names, and the values specify the desired names. It returns a new DataFrame with the renamed columns.

    In this article, I will explain the Polars DataFrame.rename() method, including its syntax, parameters, and usage, to demonstrate how it can be used to create a new DataFrame with updated column names.

    Key Points –

    <a id="h-syntax-of-polars-dataframe-rename"></a>

    Syntax of Polars DataFrame.rename()

    Let’s know the syntax of the Polars DataFrame rename() method.

    
    # Syntax of rename()
    DataFrame.rename(
        mapping: dict[str, str] | Callable[[str], str],
        *,
        strict: bool = True,
    ) → DataFrame
    

    <a id="h-parameters-of-the-polars-dataframe-rename"></a>

    Parameters of the Polars DataFrame.rename()

    Following are the parameters of the polars DataFrame.rename() method.

    <a id="h-return-value"></a>

    Return Value

    This function returns a new DataFrame with renamed columns.

    <a id="h-usage-of-polars-dataframe-rename"></a>

    Usage of Polars DataFrame.rename()

    The rename() method is used to change the names of one or more columns in a Polars DataFrame by providing a dictionary that maps existing column names to new ones.

    To run some examples of the Polars DataFrame.rename() method, let’s create a Pandas DataFrame.

    
    import polars as pl
    
    # Creating a new Polars DataFrame
    technologies= {
        'Courses':["Spark","Hadoop","Python","Pandas"],
        'Fees' :[22000,25000,20000,26000],
        'Duration':['30days','50days','40days','40days'],
        'Discount':[1000,1500,1200,2500]
    }
    
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To rename columns in a Polars DataFrame using a dictionary, you can use the .rename() method. The dictionary will map the old column names to the new ones.

    
    # Rename columns using a dictionary
    df2 = df.rename({
        'Courses': 'Course_List',
        'Fees': 'Course_Fee',
        'Duration': 'Course_Duration',
        'Discount': 'Course_Discount'
    })
    
    print("Renamed DataFrame:\n", df2)
    

    In the above example, The rename() method is used with a dictionary where the keys represent the old column names, and the values represent the new column names.

    <a id="h-rename-only-a-subset-of-columns"></a>

    Rename Only a Subset of Columns

    To rename only a subset of columns in a Polars DataFrame, you can specify a dictionary with only the columns you want to rename. The columns that are not included in the dictionary will remain unchanged.

    
    # Rename only a subset of columns
    df2 = df.rename({
        'Courses': 'Course_Name',
        'Fees': 'Course_Fee'
    })
    print("Renamed Subset DataFrame:\n", df2)
    
    # Output:
    # Renamed Subset DataFrame:
    # shape: (4, 4)
    ┌─────────────┬────────────┬──────────┬──────────┐
    │ Course_Name ┆ Course_Fee ┆ Duration ┆ Discount │
    │ ---         ┆ ---        ┆ ---      ┆ ---      │
    │ str         ┆ i64        ┆ str      ┆ i64      │
    ╞═════════════╪════════════╪══════════╪══════════╡
    │ Spark       ┆ 22000      ┆ 30days   ┆ 1000     │
    │ Hadoop      ┆ 25000      ┆ 50days   ┆ 1500     │
    │ Python      ┆ 20000      ┆ 40days   ┆ 1200     │
    │ Pandas      ┆ 26000      ┆ 40days   ┆ 2500     │
    └─────────────┴────────────┴──────────┴──────────┘
    

    Here,

    <a id="h-rename-columns-using-a-function"></a>

    Rename Columns Using a Function

    To rename columns using a function in Polars, you can use the .columns attribute to access the column names and apply a function to modify them.

    
    # Rename columns using a function (e.g., converting column names to lowercase)
    df2 = df.rename({col: col.lower() for col in df.columns})
    print("Renamed DataFrame:\n", df2)
    
    # Output:
    # Renamed DataFrame:
    # shape: (4, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ courses ┆ fees  ┆ duration ┆ discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Spark   ┆ 22000 ┆ 30days   ┆ 1000     │
    │ Hadoop  ┆ 25000 ┆ 50days   ┆ 1500     │
    │ Python  ┆ 20000 ┆ 40days   ┆ 1200     │
    │ Pandas  ┆ 26000 ┆ 40days   ┆ 2500     │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-add-a-prefix-to-column-names"></a>

    Add a Prefix to Column Names

    To add a prefix to column names in a Polars DataFrame, you can use the .columns attribute and apply a function that adds the prefix to each column name.

    
    # Add a prefix to all column names
    df2 = df.rename({col: "Tech_" + col for col in df.columns})
    print("DataFrame with Prefix:\n", df2)
    
    # Output:
    # DataFrame with Prefix:
    # shape: (4, 4)
    ┌──────────────┬───────────┬───────────────┬───────────────┐
    │ Tech_Courses ┆ Tech_Fees ┆ Tech_Duration ┆ Tech_Discount │
    │ ---          ┆ ---       ┆ ---           ┆ ---           │
    │ str          ┆ i64       ┆ str           ┆ i64           │
    ╞══════════════╪═══════════╪═══════════════╪═══════════════╡
    │ Spark        ┆ 22000     ┆ 30days        ┆ 1000          │
    │ Hadoop       ┆ 25000     ┆ 50days        ┆ 1500          │
    │ Python       ┆ 20000     ┆ 40days        ┆ 1200          │
    │ Pandas       ┆ 26000     ┆ 40days        ┆ 2500          │
    └──────────────┴───────────┴───────────────┴───────────────┘
    

    Here,

    <a id="h-add-a-suffix-to-column-names"></a>

    Add a Suffix to Column Names

    To add a suffix to column names in a Polars DataFrame, you can use a similar approach as with adding a prefix. By accessing the .columns attribute, you can apply a function that adds a suffix to each column name.

    
    # Add a suffix to all column names
    df2 = df.rename({col: col + "_info" for col in df.columns})
    print("DataFrame with Suffix:\n", df2)
    
    # Output:
    # DataFrame with Suffix:
     shape: (4, 4)
    ┌──────────────┬───────────┬───────────────┬───────────────┐
    │ Courses_info ┆ Fees_info ┆ Duration_info ┆ Discount_info │
    │ ---          ┆ ---       ┆ ---           ┆ ---           │
    │ str          ┆ i64       ┆ str           ┆ i64           │
    ╞══════════════╪═══════════╪═══════════════╪═══════════════╡
    │ Spark        ┆ 22000     ┆ 30days        ┆ 1000          │
    │ Hadoop       ┆ 25000     ┆ 50days        ┆ 1500          │
    │ Python       ┆ 20000     ┆ 40days        ┆ 1200          │
    │ Pandas       ┆ 26000     ┆ 40days        ┆ 2500          │
    └──────────────┴───────────┴───────────────┴───────────────┘
    

    Here,

    <a id="h-replace-spaces-in-column-names"></a>

    Replace Spaces in Column Names

    Similarly, to modify column names in a Polars DataFrame by replacing spaces, you can use the .rename() method or opt for a programmatic approach such as a list comprehension. This allows you to substitute spaces with another character (e.g., underscores _) or eliminate them altogether.

    
    import polars as pl
    
    # Create a DataFrame with spaces in column names
    df = pl.DataFrame({
        "Course Name": ["Spark", "Hadoop", "Python", "Pandas"],
        "Course Fees": [22000, 25000, 20000, 26000],
        "Course Duration": ["30days", "50days", "40days", "40days"]
    })
    
    # Replace spaces in column names dynamically
    df_renamed = df.rename({
        col: col.replace(" ", "_") for col in df.columns
    })
    print("DataFrame with Spaces Replaced Dynamically:\n", df_renamed)
    
    # Output:
    # DataFrame with Spaces Replaced Dynamically:
    # shape: (4, 3)
    ┌─────────────┬─────────────┬─────────────────┐
    │ Course_Name ┆ Course_Fees ┆ Course_Duration │
    │ ---         ┆ ---         ┆ ---             │
    │ str         ┆ i64         ┆ str             │
    ╞═════════════╪═════════════╪═════════════════╡
    │ Spark       ┆ 22000       ┆ 30days          │
    │ Hadoop      ┆ 25000       ┆ 50days          │
    │ Python      ┆ 20000       ┆ 40days          │
    │ Pandas      ┆ 26000       ┆ 40days          │
    └─────────────┴─────────────┴─────────────────┘
    

    Here,

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

    Conclusion

    In this article, I will explain the Polars DataFrame.rename() method and by using its syntax, parameters, and usage how we can return a new DataFrame with the updated column names. The original DataFrame remains unchanged, ensuring a non-destructive workflow that allows you to make transformations without modifying the original data.

    Happy Learning!!

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

    Related Articles

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

    References