rename a particular column in pandas in python

To rename a particular column in pandas in Python, you can use the rename() function. Here's an example:

main.py
import pandas as pd

# Create a DataFrame
data = {'Name': ['John', 'Sarah', 'Michael'],
        'Age': [25, 30, 35],
        'City': ['New York', 'London', 'Paris']}

df = pd.DataFrame(data)

# Rename the 'City' column to 'Location'
df.rename(columns={'City': 'Location'}, inplace=True)

# Output the DataFrame
print(df)
321 chars
15 lines

This will rename the 'City' column to 'Location' in the DataFrame. The columns argument of the rename() function takes a dictionary where the keys are the current column names and the values are the new column names. By setting inplace=True, the renaming is done directly on the original DataFrame without creating a new one.

The output will be:

main.py
      Name  Age  Location
0     John   25  New York
1    Sarah   30    London
2  Michael   35     Paris
104 chars
5 lines

related categories

gistlibby LogSnag