Pandas String Replacement With a Callback

If you want to replace parts of strings in a Pandas Series you can pass in a string, but if you want to keep part of the original sub-string that you are replacing you can call the replace method while passing in a function that un-packs the match object.

As an example, to add paretheses around strings that look like "Also see penguin" you can define a regular expression that has a named group in it.

PATTERN = r"Also see (?P<name>\w+)"

Then define a function that expects objects that match the pattern and creates a string using the named-group.

def see_also(match: re.match) -> str:
    """Add parentheses to Also see

    Args:
     match: regular expression match object

    Returns:
     string with the name from the object and parentheses added
    """
    return f"(Also see {match['name']})"

Then pass in the pattern and function to the replace method.

table["Animal"] = table.Animal.str.replace(PATTERN, see_also)