【问题标题】:Pandas: Select rows that contain any substring from a listPandas:从列表中选择包含任何子字符串的行
【发布时间】:2021-02-01 23:19:35
【问题描述】:

我想在包含列表中任何子字符串的列中选择这些行。这就是我现在所拥有的。

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

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

【问题讨论】:

    标签: python python-3.x pandas dataframe substring


    【解决方案1】:

    对于通过子字符串匹配的值,通过| 连接列表的所有值以获取正则表达式or - 所以获取值LIDTABLEWARE ...:

    解决方案在 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
    

    【讨论】:

    • 问题:为什么我们需要在pat 中有\b
    • @balderman - 称为单词边界,所有单词都必须匹配 - 避免在单词bobcat is nice中匹配cat,匹配cat is nice
    • 我明白了。所以pat 实际上是一个正则表达式,术语“单词边界”取自正则表达式域。谢谢。
    【解决方案2】:

    一种解决方案是使用正则表达式解析'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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 2019-04-19
      • 2020-02-23
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多