Renaming columns in Pandas

Geomario
2 min readJan 27, 2021

Renaming Pandas columns it's a basic Pandas manipulation, yet powerful—Lets program.

Renaming columns in Pandas

Let's start creating a simple DataFrame that contains 2 Pandas Series.

#1 In the code block section that corresponds to # 1, the creation of the DataFrame is set. The first Series corresponds to Animal and the second Series correspond to the speed of that animal.

#2 In the code block section # 2, we print the DataFrame to corroborate the information and the DataFrame creation.

#3 In the code block section # 3, the DataFrame is displayed. The corresponding information is in order with the animal and its correspondence speed.

#Code Block 1.0df = pd.DataFrame({'Animal': ['Wolf', 'Fox', 'Jaguar', 'American                   Bison'], 'Speed': [60 , 50, 80, 65]})      # 1print (df)                                 # 2>>> df                                     # 3
Animal Speed
0 Wolf 60
1 Fox 50
2 Jaguar 80
3 American Bison 65

We suddenly got new animal information. We notice that this DataFrame in code block 1.0, corresponds to Animal endemic to NorthAmerica. We just decided to change the Series name from “Animal” to “Animal in NA” and add the units of the speed, km/hr. Lets program.

#Code Block 2.0df.columns = ["Animal in NA", "Speed Km/hr"]    # 1print (df)                                      # 2>>> df                                          # 3
Animal in NA Speed Km/hr
0 Wolf 60
1 Fox 50
2 Jaguar 80
3 American Bison 65

#1 in the section corresponding to # 1, we apply the property df. Columns. This property entitles you to change the names of the corresponding DataFrame. You have to set the new name into a list.

#2 in section #2, we print the DataFrame to corroborate if the names have changed accordingly.

#3 in section # 3, we got the new DataFrame with the corresponding names that we define with the .columns property.

There you go, that simple! Do you know what happens when you add additional names for a non-existing Series? Give it a try and comment!

Please invite me a coffee and give me a clap 👏 and follow me!

Check some other of my tutorials. ⬇️

--

--

Geomario

👨‍💻 Software & Data Developer | Software Research Engineer | MLE