When data wrangling you might need to manipulate the name of a Pandas Series. You might need also to modify the name of one, some or all Series indexes. In this tutorial, we’ll learn to do exactly that.
Rename Pandas Series
We’ll first import Pandas into our Python development environment:
import pandas as pd
Then we’ll create a sample list and invoke the pd.Series() constructor to initial;ize our Series.
grades_l = [100, 95, 85, 82, 78]
grades_s = pd.Series(data = grades_l, name = 'my_grades' )
Let us now look into the Python Series we have just created:
print(grades_s)
0 100 1 95 2 85 3 82 4 78 Name: my_grades, dtype: int64
As you can see we have a Series named my_grades, made of a column of five int64 elements.
Now we’ll quickly go ahead and rename the Series using the pd.Series.rename() method:
grades_s.rename('my_grades_2')
The rename() method has an axis parameter, that is not used, and provided to be compatible with the parallel DataFrame method.
Note the Series name:
0 100 1 95 2 85 3 82 4 78 Name: my_grades_2, dtype: int64
Note that you you can use the inplace=True switch to persist your name change permanently:
grades_s.rename('my_grades_2', inplace=True)
Rename series index value / labels / names
We can also rename the index labels using the rename() method. We can easily pass a dictionary with the matching index labels as shown below:
rename_dict = {0:'first_exam', 1:'second_exam', 2:'third_exam'}
grades_s.rename (rename_dict)
And here’s our series:
first_exam 100 second_exam 95 third_exam 85 3 82 4 78 Name: my_grades, dtype: int64
That’s all for today, happy data wrangling 🙂