How to rename using a function?

0126

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

  1. Creating the DataFrame: We create a DataFrame df with columns 'Name' and 'Score'.
  2. Defining the Function: The rename_function takes a column name as input and returns it in uppercase.
  3. Renaming Columns: The rename() method is called with the columns parameter set to the rename_function. This applies the function to each column name.
  4. Output: The DataFrame df_renamed is 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 index parameter of the rename() 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!

0 Comments

no data
Be the first to share your comment!