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.
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.
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.
As shown in the output images, the changes were made and letters were replaced successfully.