Skip to content
Related Articles

Related Articles

Improve Article

Python | Pandas Series.str.slice_replace()

  • Last Updated : 24 Sep, 2018

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.slice_replace() method is used to replace a slice string present in Pandas series object. Since this is a pandas string method, .str has to be prefixed every time before calling this method. Otherwise, it gives an error.

Syntax: Series.str.slice_replace(start=None, stop=None, repl=None)

start: int value, tells where to start slicing
stop: int value, tells where to end slicing
repl: string value, replaces the sliced substring with this

Return type: Series with replaced values

To download the CSV used in code, 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 :
In this example, the salary column has been sliced to get values after decimal and those values (‘.0’ are replaced by ‘$’ sign). Since the salary column is imported as float64 data type, it is first converted to string using the .astype() method.

# importing pandas module 
import pandas as pd 
# making data frame 
# removing null values to avoid errors 
data.dropna(inplace = True
# start stop and step variables
start, repl = -2, '$'
# converting to string data type
data["Salary"]= data["Salary"].astype(str)
# slicing till 2nd last element
data["Salary New"]= data["Salary"].str.slice_replace(start = start, repl = repl)
# display

As shown in the output image, the Salary New column is having replaced values. “.0” has been replaced by “$” using .slice_replace() method.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :