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 –
- Renaming columns to lowercase ensures consistency across datasets and avoids case-sensitive errors.
- The
rename()method allows renaming columns using a dictionary mapping of old names to new names. - The
columnsproperty enables direct modification of column names without creating a new DataFrame. - The
str.lower()method is commonly used for converting column names to lowercase. - The
map() function can be used to enhance readability when modifying column names. - Using
enumerate()is useful when transformations depend on the column index position. - The
casefold()provides better case conversion, especially for handling internationalized text. - Directly modifying
columnsor usingrename()is more efficient than converting between Polars and Pandas.
<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,
df.columnsfetches the current column names.{col: col.lower() for col in df.columns}creates a dictionary that maps original names to lowercase names.rename({…})applies the changes to rename the columns.
<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,
df.columnsgets the list of column names.map(lambda col: (col, col.lower()), df.columns): Usesmap()to create key-value pairs where original column names are keys and lowercase column names are values.dict()converts the mapped pairs into a dictionary, which is passed torename().
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,
df.columnsfetches the current column names.[col.lower() for col in df.columns]creates a list of lowercase column names.zip(df.columns, [col.lower() for col in df.columns])pairs original names with lowercase names.dict(zip(…))converts this mapping into a dictionary, which is passed torename()function.
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,
df.columnsretrieves the current column names.[col.lower() for col in df.columns]creates a list of lowercase column names.- Assigning this list back to
df.columnsrenames all columns in place.
<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,
df.columnsretrieves the current column names.{col: col.casefold() for col in df.columns}creates a dictionary mapping original names to casefolded names.rename({…})applies the column name changes.
<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,
enumerate(df.columns)generates index-column pairs (though we don’t use the index in this case).{old_col: old_col.lower() for idx, old_col in enumerate(df.columns)}creates a dictionary mapping original column names to lowercase names.rename({…})applies the new names to the DataFrame.
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
- Convert Polars String to Integer
- Select Polars Columns by Index
- Polars Filter by Column Value
- Convert DataFrame to Series in Polars
- How to Change Position of a Column in Polars
- Reorder Columns in a Specific Order Using Polars
- How to Convert a Polars DataFrame to Python List?
- Append or Concatenate Two DataFrames in Polars
- How to Add a Column with Numerical Value in Polars
<a id="h-references"></a>
