【问题标题】:Match words in a dataframe column from a list匹配列表中数据框列中的单词
【发布时间】:2022-01-14 12:53:47
【问题描述】:

我有一个列表
a = ['apples', 'bananas', 'oranges', 'grapes']

还有一个包含一列短语的数据框

b c
there are 5 apples there are 5
here are 3 pears here are 3 pears
i want 2 grapes i want 2

我想在我的数据框中有另一列从列表 a 中删除单词(例如在数据框列 c 中)。它们需要完全匹配。

在搜索了一些正则表达式后,我想出了这个,但它似乎无法正常工作。

regex = re.compile('|'.join(re.escape(x) for x in a), re.IGNORECASE)

removed = []
for i in df['b']:
    words = re.findall(regex, str(i))
    removed.append(words)

df['c']=removed
df

也得到了这个错误:位置括号不平衡

【问题讨论】:

标签: python regex pandas dataframe


【解决方案1】:

您实际上不需要任何正则表达式,因为它们是完全匹配的。

你可以这样做:

import pandas as pd
a = ['apples', 'bananas', 'oranges', 'grapes']

df = pd.DataFrame({'b': ['there are 5 apples', 'here are 5 pears', 'I want 2 grapes']})
# for each row in `b` remove all words that are in `a`
df['c'] = df['b'].apply(lambda x: ' '.join([word for word in x.split() if word not in a]))


    b   c
0   there are 5 apples  there are 5
1   here are 5 pears    here are 5 pears
2   I want 2 grapes I want 2

【讨论】:

    【解决方案2】:

    使用str.replace:

    我稍微修改了你的正则表达式:

    regex = re.compile(fr"\s*({'|'.join(re.escape(x) for x in a)})", re.IGNORECASE)
    
    df['c'] = df['b'].str.replace(regex, '')
    print(df)
    
    # Output
                        b                 c
    0  there are 5 apples       there are 5
    1    here are 3 pears  here are 3 pears
    2     i want 2 grapes          i want 2
    

    【讨论】:

      【解决方案3】:

      你可以使用reduce:

      import re
      from functools import reduce
      
      a = ['apples', 'bananas', 'oranges', 'grapes']
      
      sentences = ["there are 5 apples", "here are 3 pears", "i want 2 grapes"]
      
      print([reduce(lambda x, p: re.sub(p, "", x), a, sentence).strip() for sentence in sentences])
      

      输出

      ['there are 5', 'here are 3 pears', 'i want 2']
      

      【讨论】:

        【解决方案4】:

        您可以将 b 列转换为单词列表,使用 explode 和 groupby 仅保留不在 a 中的那些,然后将所有内容加入回来

        代码可以是:

        # split column b into lists and explode it
        words = df['b'].str.split().explode()
        # remove words contained in a list
        words = words[~ words.isin(a)]
        
        # join everything back
        df['c'] = words.groupby(level=0).agg(list).transform(' '.join)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-12-10
          • 2020-05-09
          • 1970-01-01
          • 2020-02-02
          • 1970-01-01
          • 1970-01-01
          • 2020-09-23
          相关资源
          最近更新 更多