You can rename columns or index labels in a Pandas DataFrame using a function by passing that function to the rename() method. This is useful when you want to apply a transformation to the existing names rather than specifying new names directly.
Example of Renaming Using a Function
Here’s a step-by-step example:
import pandas as pd
# Create a sample DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Score': [85, 92, 78]
}
df = pd.DataFrame(data)
# Display the original DataFrame
print("Original DataFrame:")
print(df)
# Define a function to rename columns
def rename_function(name):
return name.upper() # Convert column names to uppercase
# Rename columns using the function
df_renamed = df.rename(columns=rename_function)
# Display the DataFrame with renamed columns
print("\nDataFrame with Renamed Columns:")
print(df_renamed)
Explanation
- Creating the DataFrame: We create a DataFrame
dfwith columns 'Name' and 'Score'. - Defining the Function: The
rename_functiontakes a column name as input and returns it in uppercase. - Renaming Columns: The
rename()method is called with thecolumnsparameter set to therename_function. This applies the function to each column name. - Output: The DataFrame
df_renamedis printed, showing the columns 'NAME' and 'SCORE'.
Important Note
- You can also use a similar approach to rename index labels by passing the function to the
indexparameter of therename()method.
Further Learning
For more information on renaming and DataFrame operations, consider checking:
If you have any more questions or need additional examples, feel free to ask!
