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)
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.
import pandas as pd
data.dropna(inplace = True )
start, repl = - 2 , '$'
data[ "Salary" ] = data[ "Salary" ].astype( str )
data[ "Salary New" ] = data[ "Salary" ]. str .slice_replace(start = start, repl = repl)
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...