Python - Замена слов из списка в DataFrame шаблоном Regex - PullRequest
2 голосов
/ 04 апреля 2020

У меня есть следующий список и 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']})

Я хочу заменить строки из mylist, если они найдены внутри DataFrame. Я могу заменить некоторые, используя следующий шаблон регулярных выражений:

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

Однако это не все экземпляры. Мой желаемый вывод следующий:

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

Ответы [ 2 ]

5 голосов
/ 04 апреля 2020

Вы должны использовать флаг регулярного выражения ?i, который делает ваши замены нечувствительными к регистру, а также удаляет специальные символы:

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

Или вы можете добавить специальные символы в свой словарь, чтобы вы не звонить DataFrame.replace дважды:

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
0 голосов
/ 04 апреля 2020

Другое решение

Использование Pandas Ser ie str.replace() метод

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, '')

К сожалению, этот метод недоступен в DataFrame (пока?).

Приведенное здесь решение не является идеальным, но оно не изменяет список ввода до применения функции.



Дополнительная помощь:

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

...