Tutorials
pandas
+1

Renaming Columns in a Pandas DataFrame

Python's rename column is a method used to change the column names with pandas' rename function. It's useful when you load a tabular dataset that has no column names or if you want to assign different names to specific columns.

Syntax

Its syntax is given as:

df.rename(columns = d, inplace = False)

Where d is a dictionary, and the keys are the columns you want to change. The values are the new names for these columns. The code inplace = False means the result would be stored in a new DataFrame instead of the original one.

Renaming Columns

You have the following dataset called df2_melted.

print(df2_melted)
        Country variable     value
0   Afghanistan    Y1980  21.48678
1       Albania    Y1980  25.22533
2       Algeria    Y1980  22.25703
3   Afghanistan    Y1981  21.46552
4       Albania    Y1981  25.23981
5       Algeria    Y1981  22.34745
6   Afghanistan    Y1982  21.45145
7       Albania    Y1982  25.25636
8       Algeria    Y1982  22.43647
9   Afghanistan    Y1983  21.43822
10      Albania    Y1983  25.27176
11      Algeria    Y1983  22.52105

With this dataset, we want to do the following:

  • Import pandas as pd.
  • Rename the variable column of df2_melted to Year and the value column to Income and assign it to df2_tidy.
  • Finally, print the updated dataframe.
# Import pandas
import pandas as pd

# Rename the columns of df2_melted: df2_tidy
df2_tidy = df2_melted.rename(columns = {'variable': 'Year', 'value': 'Income'}, inplace = False)

# Print out df2_tidy
print(df2_tidy)

When you run the above code, it produces the following result:

        Country   Year    Income
0   Afghanistan  Y1980  21.48678
1       Albania  Y1980  25.22533
2       Algeria  Y1980  22.25703
3   Afghanistan  Y1981  21.46552
4       Albania  Y1981  25.23981
5       Algeria  Y1981  22.34745
6   Afghanistan  Y1982  21.45145
7       Albania  Y1982  25.25636
8       Algeria  Y1982  22.43647
9   Afghanistan  Y1983  21.43822
10      Albania  Y1983  25.27176
11      Algeria  Y1983  22.52105

Try it for yourself.

To learn more about Tidy Data and Messy Data, please check out the interactive exercise from our course Tidy Data in Python.

This content is taken from DataCamp’s Tidy Data in Python course by Vincent Lan.