Pandas Series str function translate() in Python
The Pandas Series str function translate() used to replace a character described in a dictionary or in a mapping table. A string characters which are not described in the dictionary / mapping table will remain same in the resulting Series object. It returns Series or Index that includes string after matching replacements.
Syntax
 1 Series.str.translate(table)
table : A table that describe the mapping for the characters.
translate() function
 1 import pandas as pd
 2 import numpy as np
 3 
 4 ser = pd.Series(['Python', 'Hello', np.nan, 'World !'])
 5                 
 6 print('The original Series object :')
 7 print(ser)
 8 
 9 mapper = str.maketrans('o', 'O')
 10 res = ser.str.translate(mapper)
 11 
 12 print('The translated Series elements :')
 13 print(res)
In the above example, a Series object is created by passing an array of string. A translate() function is called by passing a mapper object that replaces all the occurrence of matches and assign result to the variable that will be printed on console.
Output
 1 The original Series object :
 2 0     Python
 3 1      Hello
 4 2        NaN
 5 3    World !
 6 dtype: object
 7 The translated Series elements :
 8 0     PythOn
 9 1      HellO
 10 2        NaN
 11 3    WOrld !
 12 dtype: object

Example 2

Example 2
 1 import pandas as pd
 2 
 3 ser = pd.Series(['#welcome', '#to', '#IOGyan'])
 4                 
 5 print('The original Series object :')
 6 print(ser)
 7 
 8 mapper = str.maketrans('#', '_')
 9 res = ser.str.translate(mapper)
 10 
 11 print('The translated Series elements :')
 12 print(res)
In the above example, a Series object is created by passing an array of string. A translate() function is called by passing a mapper object that replaces all the occurrence of matches and assign result to the variable that will be print.
Output
 1 The original Series object :
 2 0    #welcome
 3 1         #to
 4 2     #IOGyan
 5 dtype: object
 6 The translated Series elements :
 7 0    _welcome
 8 1         _to
 9 2     _IOGyan
 10 dtype: object
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us