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