Lokesh
Lokesh

Reputation: 89

Python - Replacing words from list in DataFrame with Regex pattern

I have the following list and DataFrame:

mylist = ['foo', 'bar', 'baz']
df = pd.DataFrame({'Col1': ['fooThese', 'barWords', 'baz are', 'FOO: not', 'bAr:- needed'],
                   'Col2': ['Baz:Neither', 'Foo Are', 'barThese', np.nan, 'but this is fine']})

I want to replace the strings from mylist if found inside the DataFrame. I am able to replace some using the following Regex Pattern:

pat = '|'.join([r'\b{}'.format(w) for w in mylist])
df2 = df.replace(pat, '', regex=True)

However this doesn't place all the instances. My desired output is the following:

    Col1     Col2
0   These    Neither
1   Words    Are
2   are      These
3   not      NaN
4   needed   but this is fine

Upvotes: 2

Views: 1456

Answers (2)

swiss_knight
swiss_knight

Reputation: 7901

An other solution

Using Pandas Serie str.replace() method

import pandas as pd
mylist = ['foo', 'bar', 'baz']
df = pd.DataFrame({'Col1': ['fooThese', 'barWords', 'baz are', 'FOO: not', 'bAr:- needed'],
                   'Col2': ['Baz:Neither', 'Foo Are', 'barThese', np.nan, 'but this is fine']})

def replace_str_in_df_with_list(df, list, subst_string):
    """ Function which replaces strings in a DataFrame based on a list of strings.

    Parameters:
    ----------
    df :  <pd.DataFrame> instance
        The input DataFrame on which to perform the substitution.
    list : list
        The list of strings to use for the substitution.
    subst_string : str
        The substitution string.

    Returns:
    -------
    new_df : <pd.DataFrame> instance
        A new DataFrame with strings replaced.

    """
    df_new = df.copy()
    subst_string = str(subst_string)
    # iterate over each columns as a pd.Series() to use that method
    for c in df_new:
        # iterate over the element of the list
        for elem in list:
            df_new[c] = df_new[c].str.replace(elem, subst_string, case=False)

    return(df_new)

df2 = replace_str_in_df_with_list(df, mylist, '')

Unfortunately this method is not available on DataFrame (yet?).

The solution provided here is not perfect, but it doesn't modify the input list prior to applying the function.



More help:

https://pandas.pydata.org/pandas-docs/stable/search.html?q=replace

Upvotes: 1

Erfan
Erfan

Reputation: 42916

You have to use the ?i regex flag which makes your replacements not case sensitive, also remove special characters:

mydict = {f'(?i){word}': '' for word in mylist}
df2 = df.replace(mydict, regex=True).replace('[:-]', '', regex=True)

      Col1              Col2
0    These           Neither
1    Words               Are
2      are             These
3      not               NaN
4   needed  but this is fine

Or you can add the special characters to your dictionary, so you don't have to call DataFrame.replace twice:

mydict = {f'(?i){word}': '' for word in mylist}#.update({'[:-]': ''})
mydict['[:-]'] = ''
df2 = df.replace(mydict, regex=True)

      Col1              Col2
0    These           Neither
1    Words               Are
2      are             These
3      not               NaN
4   needed  but this is fine

Upvotes: 5

Related Questions