Open In App

Python | Pandas Series.str.slice_replace()

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.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)

Parameters:
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
data.head(10)


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


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