Pandas:Select 行包含列表中的任何子字符串

Pandas: Select rows that contain any substring from a list

我想 select 包含列表中任何子字符串的列中的那些行。这是我目前拥有的。

product = ['LID', 'TABLEWARE', 'CUP', 'COVER', 'CONTAINER', 'PACKAGING']

df_plastic_prod = df_plastic[df_plastic['Goods Shipped'].str.contains(product)]

df_plastic_prod.info()

样本df_plastic

Name          Product
David        PLASTIC BOTTLE
Meghan       PLASTIC COVER
Melanie      PLASTIC CUP 
Aaron        PLASTIC BOWL
Venus        PLASTIC KNIFE
Abigail      PLASTIC CONTAINER
Sophia       PLASTIC LID

需要 df_plastic_prod

Name          Product
Meghan       PLASTIC COVER
Melanie      PLASTIC CUP 
Abigail      PLASTIC CONTAINER
Sophia       PLASTIC LID

提前致谢!感谢您对此提供的任何帮助!

一种解决方案是使用正则表达式解析 'Product' 列,并测试提取的值是否在 product 列表中,然后根据结果过滤原始 DataFrame。

在这种情况下,使用了一个非常简单的正则表达式模式 ((\w+)$),它匹配一行末尾的单个单词。

示例代码:

df.iloc[df['Product'].str.extract('(\w+)$').isin(product).to_numpy(), :]

输出:

      Name            Product
1   Meghan      PLASTIC COVER
2  Melanie        PLASTIC CUP
5  Abigail  PLASTIC CONTAINER
6   Sophia        PLASTIC LID

设置:

product = ['LID', 'TABLEWARE', 'CUP', 
           'COVER', 'CONTAINER', 'PACKAGING']

data = {'Name': ['David', 'Meghan', 'Melanie', 
                 'Aaron', 'Venus', 'Abigail', 'Sophia'],
        'Product': ['PLASTIC BOTTLE', 'PLASTIC COVER', 'PLASTIC CUP', 
                    'PLASTIC BOWL', 'PLASTIC KNIFE', 'PLASTIC CONTAINER',
                    'PLASTIC LID']}
    
df = pd.DataFrame(data)

对于通过子字符串匹配的值,通过 | 加入列表的所有值对于正则表达式 or - 所以获取值 LIDTABLEWARE ...:[=​​16 =]

解决方案也适用于 list 中的 2 个或更多单词。

pat = '|'.join(r"\b{}\b".format(x) for x in product)
df_plastic_prod = df_plastic[df_plastic['Product'].str.contains(pat)]
print (df_plastic_prod)
      Name            Product
1   Meghan      PLASTIC COVER
2  Melanie        PLASTIC CUP
5  Abigail  PLASTIC CONTAINER
6   Sophia        PLASTIC LID