• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:17 mins read
You are currently viewing How to Rename a Pandas Series

Pandas Series.rename() function is used to rename/change/alter Series index labels or names for the given Series object. We can rename values from the given Pandas Series object based on the labels using rename() function. In this article, I will explain Series.rename() and use this function how to rename/change/alter Series object values by index labels.

Advertisements

Key Points –

  • Determine the Series object within your DataFrame that requires renaming.
  • Access the rename() function provided by Pandas to rename the Series.
  • Define the new name for the Series within the rename() function.
  • Assign the output of the rename() operation back to the original Series variable or to a new variable if necessary.
  • Apply the rename() function from the Pandas library to rename the Series, specifying the new name within the method.
  • Confirm the renaming operation by reviewing the Series or examining the DataFrame containing the Series to ensure the new name has been applied as intended.

Quick Examples of Series Rename

If you hurry below are quick examples of how to rename a pandas Series.


# Quick examples of series rename

# Example 1: Use series.rename() function
ser2 = ser.rename('Courses')

# Example 2: Use pandas.Series object
ser.name = 'Courses'

# Example 3: Use rename pandas series & inplace = true
ser.rename("Courses", inplace=True)

# Example 4: Use series.to_frame() function to rename series
ser2 =ser.to_frame("Courses")["Courses"]

# Example 5: Use series.rename() and lambda
ser2 = ser.rename(lambda x: x ** 2)

# Example 6: Use series.rename() function to changes labels
ser2 = ser.rename({1: 3, 3: 5})

# Example 7: Create the MultiIndex using series.rename() function
ser = pd.Series(['Java','Spark','PySpark','Pandas','NumPy'])
index = pd.MultiIndex.from_product([['Names'], [1000, 2000, 1500, 2500, 3000]], names =['Level 1', 'Level 2'])
ser.index = index
ser2 = ser.rename(level = 1, index = 'Fee')

Syntax of Pandas Series.rename()

Following is the syntax to create Series.rename() function.


# Syntax of Series.rename()
Series.rename(index=None, *, axis=None, copy=True, inplace=False, level=None, errors='ignore')

Parameters of rename()

Following are the parameters of rename().

  • index – dict-like or functions are transformations to apply to the index. Scalar or hashable sequence-like will alter the Series.name attribute.
  • axis – {0 or ‘index’}: The unused parameter needed for compatibility with DataFrame.
  • copy – bool, default True. Whether to copy underlying data.
  • inplace – This boolean parameter is default False. Whether to return a new Series. If True the value of copy is ignored.
  • level – In the case of MultiIndex, only rename labels in the specified level.

It returns a series with names or index labels altered.

Create Pandas Series

Pandas Series is a one-dimensional, Index-labeled data structure available only in the Pandas library. It can store all the datatypes such as strings, integers, float, and other python objects. We can access each element in the Series with the help of corresponding default indices.

Now, let’s create pandas series using a list of values.


import pandas as pd

# Create Pandas Series from list
data = ['Java', 'Spark', 'PySpark', 'Pandas', 'NumPy']
series = pd.Series(data, index=[0, 1, 2, 3, 4])
print(series)

Yields below output.


# Output:
0       Java
1      Spark
2    PySpark
3     Pandas
4      NumPy
dtype: object

Usage Series.rename() Function

Series.rename() function is used to rename the name object of given pandas Series. For example, Let’s create a Series.


import pandas as pd
  
# Create the Series
ser = pd.Series(['Java','Spark','PySpark','Pandas','NumPy'], index=[0,1,2,3,4])
print(ser)

Here, I have not given a name to the Series column. If you want you can add a name to a column of the Series by using the name parameter while using the Series() constructor.

Now, let’s rename the Series column name.


# Use series.rename() function
ser2 = ser.rename('Courses')
print(ser2)

# Use pandas.Series object
ser.name = 'Courses'
print(ser)

# Use rename pandas series & inplace = true
ser2 = ser.rename("Courses", inplace=True)
print(ser2)

Yields below output.


# Output:
0       Java
1      Spark
2    PySpark
3     Pandas
4      NumPy
Name: Courses, dtype: object

Use series.to_frame() Function to Rename Series

The to_frame() function in Pandas is used to convert a Series to a DataFrame. While it doesn’t directly rename the Series, you can rename the resulting DataFrame columns after converting the Series.


# Use series.to_frame() function to rename series
ser2 =ser.to_frame("Courses")["Courses"]
print(ser2)

Yields the same output as above.

Use series.rename() and Lambda

We can also use Pandas series.rename() along with the lambda function. The following example returns square index values from a series where values are changed in the labels index.


# Use series.rename() and lambda
ser2 = ser.rename(lambda x: x ** 2)
print(ser2)

Yields below output.


# Output:
0        Java
1       Spark
4     PySpark
9      Pandas
16      NumPy
dtype: object

Pandas series.rename() function also used to rename multiple labels index values or all indexes of the pandas Series. For examples.


# Use series.rename() function to changes labels
ser2 = ser.rename({1: 3, 3: 5})
print(ser2)

Yields below output.


# Output:
0       Java
3      Spark
2    PySpark
5     Pandas
4      NumPy
dtype: object

Using series.rename() Function to Create MultiIndex

We can also use Series.rename() function to rename the multi-index axis of the given Series object. Use this function to rename the 1st level of the series.


# Create the MultiIndex using series.rename() function
ser = pd.Series(['Java','Spark','PySpark','Pandas','NumPy'])
index = pd.MultiIndex.from_product([['Names'], [1000, 2000, 1500, 2500, 3000]], names =['Level 1', 'Level 2'])
ser.index = index
ser2 = ser.rename(level = 1, index = 'Fee')
print(ser2)

Yields below output.


# Output:
Level 1  Level 2
Names    1000          Java
         2000         Spark
         1500       PySpark
         2500        Pandas
         3000         NumPy
Name: Fee, dtype: object

Complete Example of Rename Pandas Series


import pandas as pd
  
# Create the Series
ser = pd.Series(['Java','Spark','PySpark','Pandas','NumPy'], index=[0,1,2,3,4])
print(ser)

# Use series.rename() function
ser2 = ser.rename('Courses')
print(ser2)

# Use pandas.Series object
ser.name = 'Courses'
print(ser)

# Use rename pandas series & inplace = true
ser2 = ser.rename("Courses", inplace=True)
print(ser2)

# Use series.to_frame() function to rename series
ser2 =ser.to_frame("Courses")["Courses"]
print(ser2)

# Use series.rename() and lambda
ser2 = ser.rename(lambda x: x ** 2)
print(ser2)

# Use series.rename() function to changes labels
ser2 = ser.rename({1: 3, 3: 5})
print(ser2)

# Create the MultiIndex using series.rename() function
ser = pd.Series(['Java','Spark','PySpark','Pandas','NumPy'])
index = pd.MultiIndex.from_product([['Names'], [1000, 2000, 1500, 2500, 3000]], names =['Level 1', 'Level 2'])
ser.index = index
ser2 = ser.rename(level = 1, index = 'Fee')
print(ser2)

Frequently Asked Questions on Rename a Pandas Series

How do I rename a Series in Pandas?

You can rename a Pandas Series using the rename() method. Provide the new name as an argument to this method.

Can I rename only the index of a Series?

You can rename only the index of a Series using the rename() method by specifying the index parameter.

Does renaming a Series modify the original Series?

By default, the rename() method returns a new Series with the specified changes, leaving the original Series unchanged. However, you can use the inplace=True parameter to perform the renaming operation in place.

Can I rename a Series while converting it to a DataFrame using to_frame()?

You can rename a Series while converting it to a DataFrame using the to_frame() function in Pandas. You can specify the desired name for the Series when converting it to a DataFrame.

Can I rename a Series to have an empty name or a name with special characters?

You can rename a Series to have an empty name or a name with special characters. However, it’s generally recommended to use descriptive and valid names for better code readability and compatibility.

What is the difference between renaming a Series and renaming its index?

Renaming a Series involves changing the name of the Series itself, while renaming its index involves changing the labels of the index without altering the Series values.

Conclusion

In this article, I have explained how to rename a pandas series using Series.rename() function. and Also explained how to rename series with lambda function, series.to_frame(), create multi-index labels with examples.

Happy Learning !!

Related Articles

References