Open In App

Python | Pandas Series.str.translate()

Improve
Improve
Like Article
Like
Save
Share
Report

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)

Parameters:
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
data


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


Last Updated : 29 Sep, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads