To change a column’s name in a pandas DataFrame in Python, the easiest way is that you can use the pandas rename() function.
import pandas as pd
df = pd.DataFrame({"some_column": [1, 2, 3]})
print(df)
df.rename(columns={"some_column": "changed_name"}, inplace=True)
print(df)
#Output:
some_column
0 1
1 2
2 3
changed_name
0 1
1 2
2 3
When working with collections of data, the ability to easily be able to change the names of your variables and datasets is useful.
One such case is if you want to change a column name in a pandas DataFrame.
To change a column’s name in a pandas DataFrame in Python, the easiest way is that you can use the pandas rename() function.
To change a column’s name with rename(), just pass a dictionary to the ‘columns’ parameter with keys and values which represent the columns you want to rename and the new names for the columns, respectively.
Below is a simple example showing you how to rename and change the names of columns in a pandas DataFrame in Python.
import pandas as pd
df = pd.DataFrame({"some_column": [1, 2, 3]})
print(df)
df.rename(columns={"some_column": "changed_name"}, inplace=True)
print(df)
#Output:
some_column
0 1
1 2
2 3
changed_name
0 1
1 2
2 3
Change Column Names of Multiple Columns in pandas
If you want to change the name of multiple columns, you can do this with the pandas rename() function.
To change the name of multiple columns, you just need to pass more key/value pairs to the ‘columns’ parameter.
Below shows a simple example of how you can change the names of multiple columns in a pandas DataFrame in Python.
import pandas as pd
df = pd.DataFrame({"one": [1, 2, 3], "two":[2,3,4]})
print(df)
df.rename(columns={"one": "first", "two":"second"}, inplace=True)
print(df)
#Output:
one two
0 1 2
1 2 3
2 3 4
first second
0 1 2
1 2 3
2 3 4
Hopefully this article has been useful for you to learn how to change column names in pandas in your Python code.