Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.replace()
function is used to replace values given in to_replace with value. The values of the Series are replaced with other values dynamically.
Syntax:
Series.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’)
Parameters :
to_replace : How to find the values that will be replaced.
value : Value to replace any values matching to_replace with.
inplace : If True, in place.
limit : Maximum size gap to forward or backward fill.
regex : Whether to interpret to_replace and/or value as regular expressions
method : The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.
Returns : Object after replacement.
Example #1: Use Series.replace()
function to replace some values from the given Series object.
Python3
import pandas as pd
sr = pd.Series([ 10 , 25 , 3 , 11 , 24 , 6 ])
index_ = [ 'Coca Cola' , 'Sprite' , 'Coke' , 'Fanta' , 'Dew' , 'ThumbsUp' ]
sr.index = index_
print (sr)
|
Output :
Coca Cola 10
Sprite 25
Coke 3
Fanta 11
Dew 24
ThumbsUp 6
dtype: int64
Now we will use Series.replace()
function to replace the old values with the new ones.
Python3
result = sr.replace(to_replace = 3 , value = 1000 )
print (result)
|
Output :
Coca Cola 10
Sprite 25
Coke 1000
Fanta 11
Dew 24
ThumbsUp 6
dtype: int64
As we can see in the output, the Series.replace()
function has successfully replaced the old value with the new one.
Example #2 : Use Series.replace()
function to replace some values from the given Series object.
Python3
import pandas as pd
sr = pd.Series([ 'New York' , 'Chicago' , 'Toronto' , 'Lisbon' , 'Rio' ])
index_ = [ 'City 1' , 'City 2' , 'City 3' , 'City 4' , 'City 5' ]
sr.index = index_
print (sr)
|
Output :
City 1 New York
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Rio
dtype: object
Now we will use Series.replace()
function to replace the old values with the new ones using a list.
Python3
result = sr.replace(to_replace = [ 'New York' , 'Rio' ], value = [ 'London' , 'Brisbane' ])
print (result)
|
Output :
City 1 London
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Brisbane
dtype: object
As we can see in the output, the Series.replace()
function has successfully replaced the old value with the new one using the list.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Aug, 2023
Like Article
Save Article