How to rename a single column?

0253

To rename a single column in a Pandas DataFrame, you can use the rename() method and specify the current column name along with the new name in a dictionary. This allows you to change just one column without affecting the others.

Example of Renaming a Single Column

Here’s a step-by-step example:

import pandas as pd

# Create a sample DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Score': [85, 92, 78],
    'Age': [20, 21, 19]
}

df = pd.DataFrame(data)

# Display the original DataFrame
print("Original DataFrame:")
print(df)

# Rename a single column
df_renamed = df.rename(columns={'Name': 'First Name'})

# Display the renamed DataFrame
print("\nRenamed DataFrame:")
print(df_renamed)

Explanation

  1. Creating the DataFrame: We first create a DataFrame df with columns 'Name', 'Score', and 'Age'.
  2. Renaming the Column: The rename() method is called with a dictionary in the columns parameter. The key is the current column name ('Name'), and the value is the new name ('First Name').
  3. Output: The renamed DataFrame df_renamed is printed, showing 'First Name' instead of 'Name'.

Important Note

  • The rename() method returns a new DataFrame with the updated column name. If you want to modify the original DataFrame in place, you can use the inplace=True parameter:
df.rename(columns={'Name': 'First Name'}, inplace=True)

Further Learning

For more details on renaming columns and other DataFrame operations, you can check:

If you have any more questions or need further examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!