Pandas DataFrame – Change Column Names

You can access Pandas DataFrame columns using DataFrame.columns property. We can assign an array with new column names to the DataFrame.columns property.

Note: Length of new column names arrays should match number of columns in the DataFrame.

Example 1 – Change Column Names of Pandas DataFrame

In the following example, we take a DataFrame with some initial column names and change these column names to new values.

Python Example

</>
Copy
import pandas as pd

#initialize a dataframe
df = pd.DataFrame({
	'a':[14, 52, 46],
	'b':[32, 85, 64],
	'c':[88, 47, 36]})
	
#change column names
df.columns = ['d', 'e', 'f']

#print the dataframe
print(df)

Output

    d   e   f
0  14  32  88
1  52  85  47
2  46  64  36

Example – 2 [Negative Scenario] – Column Names Array Length not same as that of Columns in DataFrame

In this example, we shall assign DataFrame.columns an array that has length greater than that of columns in the DataFrame. As the lengths are not same, the program should throw ValueError.

Python Example

</>
Copy
import pandas as pd

#initialize a dataframe
df = pd.DataFrame({
	'a':[14, 52, 46],
	'b':[32, 85, 64],
	'c':[88, 47, 36]})
	
#change column names
df.columns = ['d', 'e', 'f', 'g']

#print the dataframe
print(df)

Output

ValueError: Length mismatch: Expected axis has 3 elements, new values have 4 elements

We get a Value Error with the message that there is a length mismatch for old column names and new column namess.

Conclusion

In this Pandas Tutorial, we learned how to change the column names of a DataFrame.