Python | Pandas Series.str.translate()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas str.translate() is one of most important and complex string method. It uses a translate table to translate the caller series of string according to the translate table. If there are more than one values to be translated, a dictionary is passed to maketrans function to create a translate table.

Syntax: Series.str.translate(table, deletechars=None)

table: Translation table made of dictionary in Python3 and lists in Python2.
deletechars: String type, characters to be deleted. This Parameter works properly in Python2 only(till pandas v0.23)

Return type: Series of strings with translated values

To download the data set used in following example, click here.

In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.

Example #1:
In this example, a translation table is created through a dictionary. The dictionary has a, b and c as its keys and X, Y and Z as values respectively. Translation table is created to replace a, b and c with X, Y and Z respectively. This table is passed to str.translate() method to make changes accordingly.





# importing pandas module 
import pandas as pd
# reading csv file from url 
# dropping null value columns to avoid errors
data.dropna(inplace = True)
# creating dictionary for trans table
trans_dict ={"a": "X", "b": "Y", "c": "Z"}
# creating translate table from dictionary
trans_table ="abc".maketrans(trans_dict)
# translating through passed transtable
data["Name"]= data["Name"].str.translate(trans_table)
# display


As shown in the output images, the changes were made and letters were replaced successfully.

My Personal Notes arrow_drop_up

Developer in day, Designer at night GSoC 2019 with Python Software Foundation (EOS Design system)

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.