pandas.rename() example in python

The pandas.rename() function is used to rename columns or rows in a pandas DataFrame. Here's an example of how to use it in Python:

main.py
import pandas as pd

# Create a DataFrame
data = {'Name': ['John', 'Anna', 'Peter'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)

# Original DataFrame
print("Original DataFrame:")
print(df)

# Renaming columns using pandas.rename()
df = df.rename(columns={'Name': 'First Name', 'City': 'City Name'})

# Updated DataFrame
print("\nDataFrame after renaming columns:")
print(df)
434 chars
19 lines

In the above example, we have a DataFrame with columns 'Name', 'Age', and 'City'. We want to rename the 'Name' column to 'First Name' and the 'City' column to 'City Name'. The pandas.rename() function takes a dictionary as an argument, where the keys are the old column names and the values are the new column names. The function updates the DataFrame with the new column names.

Output:

main.py
Original DataFrame:
   Name  Age      City
0  John   25  New York
1  Anna   30     Paris
2 Peter   35    London

DataFrame after renaming columns:
  First Name  Age City Name
0       John   25  New York
1       Anna   30     Paris
2      Peter   35    London
259 chars
12 lines

Note that pandas.rename() returns a new DataFrame with the updated column names, so we assign the returned DataFrame back to df.

related categories

gistlibby LogSnag