Removing any string from within a string in Pandas

Often, you'll find that you need to remove one or more characters from within a string. Real-world examples of this include internal abbreviations such as FKA (Formerly Known As) or suffixes such as Jr. or Sr.

Getting ready

Continue using the customer's DataFrame you created earlier, or import the file into a new DataFrame.

How to do it…

def remove_internal_abbreviations(s, thing_to_replace, replacement_string): """ Helper function to remove one or movre characters from a string s: the full string thing_to_replace: what you want to replace in the given string replacement_string: the string to use as a replacement """ try: s = s.replace(thing_to_replace, replacement_string) except: pass return s customers['last_name'] ...

Get Python Business Intelligence Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.