Built with Tutify.io

    AIStudyLabs

    Polars Rename Columns to Lowercase

    Polars Rename Columns to Lowercase

    In Polars, you can rename all columns to lowercase using the rename() method with a dictionary comprehension. Renaming columns to lowercase in Polars means transforming all column names in a DataFrame to be in lowercase format. This is useful for maintaining consistency, avoiding case-sensitivity issues, and improving readability. In this article, I will demonstrate how to rename columns to lowercase in a Polars DataFrame.

    Key Points –

    <a id="h-usage-of-polars-rename-columns-to-lowercase"></a>

    Usage of Polars Rename Columns to Lowercase

    Renaming all columns to lowercase in Polars is a common practice for standardizing column names. This ensures consistency, avoids case-sensitive issues, and improves compatibility when working with different datasets.

    To run some examples of polars rename columns to lowercase, let’s create a Polars DataFrame.

    
    import polars as pl
    
    technologies= {
        'COURSES':["Spark","PySpark","Hadoop","Python","Pandas"],
        'FEES' :[22000,25000,23000,24000,26000],
        'DURATION':['30days','50days','35days', '40days','55days'],
        'DISCOUNT':[1000,2300,1000,1200,2500]
              }
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    You can rename all column names to lowercase using either the rename() method or by modifying df.columns. The rename() method allows you to update column names by passing a dictionary that maps existing names to new ones. To convert all column names to lowercase, you can use rename() with dictionary comprehension.

    
    # Rename all column names to lowercase
    # Using rename() with dictionary comprehension
    df2 = df.rename({col: col.lower() for col in df.columns})
    print("Updated DataFrame with Lowercase Column Names:\n", df2)
    

    Here,

    <a id="h-rename-all-columns-to-lowercase-using-map"></a>

    Rename All Columns to Lowercase using map()

    You can use the map() function to convert all column names to lowercase, enhancing readability. Python's built-in map() function provides a clean and functional approach to renaming column names in lowercase.

    
    # Rename all columns to lowercase using map()
    df2 = df.rename(dict(map(lambda col: (col, col.lower()), df.columns)))
    print("Updated DataFrame with Lowercase Column Names:\n", df2)
    
    # Output:
    # Updated DataFrame with Lowercase Column Names:
    # shape: (5, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ courses ┆ fees  ┆ duration ┆ discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Spark   ┆ 22000 ┆ 30days   ┆ 1000     │
    │ PySpark ┆ 25000 ┆ 50days   ┆ 2300     │
    │ Hadoop  ┆ 23000 ┆ 35days   ┆ 1000     │
    │ Python  ┆ 24000 ┆ 40days   ┆ 1200     │
    │ Pandas  ┆ 26000 ┆ 55days   ┆ 2500     │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    Yields the same output as above.

    <a id="h-rename-all-columns-to-lowercase-using-list-and-zip"></a>

    Rename All Columns to Lowercase Using list() and zip()

    You can use zip() with list() to create a dictionary that maps old column names to their lowercase versions and then apply the rename() method. This approach in Polars is both efficient and easy to read.

    
    # Rename all columns to lowercase using list() and zip()
    df2 = df.rename(dict(zip(df.columns, [col.lower() for col in df.columns])))
    print("Updated DataFrame with Lowercase Column Names:\n", df2)
    

    Here,

    Yields the same output as above.

    <a id="h-rename-all-columns-to-lowercase-using-columns-property"></a>

    Rename All Columns to Lowercase Using columns Property

    You can rename all columns to lowercase using the columns attribute in Polars, making it a simple and efficient approach. The columns property enables direct modification of column names in a Polars DataFrame.

    
    # Renaming all columns to lowercase using .columns property
    df2 = df.columns = [col.lower() for col in df.columns]
    print("Updated DataFrame with Lowercase Column Names:\n", df2)
    
    # Output:
    # Updated DataFrame with Lowercase Column Names:
    # ['courses', 'fees', 'duration', 'discount']
    

    Here,

    <a id="h-rename-all-columns-to-lowercase-using-str-casefold-instead-of-str-lower"></a>

    Rename All Columns to Lowercase Using str.casefold() Instead of str.lower()

    You can rename all columns to lowercase using str.casefold() instead of str.lower(). The casefold() method provides a more aggressive case conversion, making it ideal for case-insensitive comparisons. It is especially useful for handling special characters and working with internationalized text.

    
    # Rename all columns to lowercase using str.casefold()
    df2 = df.rename({col: col.casefold() for col in df.columns})
    print("Updated DataFrame with Lowercase Column Names:\n", df2)
    
    # Output:
    # Updated DataFrame with Lowercase Column Names:
    # shape: (5, 4)
    ┌─────────┬───────┬──────────┬──────────┐
    │ courses ┆ fees  ┆ duration ┆ discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---      │
    │ str     ┆ i64   ┆ str      ┆ i64      │
    ╞═════════╪═══════╪══════════╪══════════╡
    │ Spark   ┆ 22000 ┆ 30days   ┆ 1000     │
    │ PySpark ┆ 25000 ┆ 50days   ┆ 2300     │
    │ Hadoop  ┆ 23000 ┆ 35days   ┆ 1000     │
    │ Python  ┆ 24000 ┆ 40days   ┆ 1200     │
    │ Pandas  ┆ 26000 ┆ 55days   ┆ 2500     │
    └─────────┴───────┴──────────┴──────────┘
    

    Here,

    <a id="h-rename-all-columns-to-lowercase-using-enumerate"></a>

    Rename All Columns to Lowercase Using enumerate()

    You can rename all columns to lowercase in Polars using the enumerate() function. This method is useful when you need both the index and column name during renaming.

    
    # Rename all columns to lowercase using enumerate()
    df2 = df.rename({old_col: old_col.lower() for idx, old_col in enumerate(df.columns)})
    print("Updated DataFrame with Lowercase Column Names:\n", df2)
    

    Here,

    Yields the same output as above.

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

    Conclusion

    In conclusion, you can rename column names to lowercase using various approaches, such as the rename() method, modifying df.columns, or utilizing functions like map(), zip(), casefold(), and enumerate(). Each approach provides flexibility, making it easy to adapt based on readability, performance, and specific requirements.

    Happy Learning!!

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

    Related Articles

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

    References