【问题标题】:Creating a list of Or's and then filtering dataframe using that list Pandas/Python创建 Or 的列表,然后使用该列表 Pandas/Python 过滤数据框
【发布时间】:2014-07-02 23:26:11
【问题描述】:

我有一个如下的数据框:

 Supplier  ProductDescription   Manufacturer
   Dell        computer              Dell
    N/A        Dell computer         N/A
   Apple       imac                 Apple
   OfficeMax   lenovo               lenovo ...etc

我想按包含某些单词但不重复计算的行过滤掉这个数据框。所以本质上,我想保留这些包含“Dell”或“c​​omputer”或“lenovo”的行。

获得:

   Supplier  ProductDescription   Manufacturer
   Dell        computer              Dell
    N/A        Dell computer         N/A
   OfficeMax   lenovo               lenovo 

我所做的是创建一个组合列:

  df['combine']=df.apply(lambda x:'%s,%s,%s' % (x['Supplier'],x['Product Description'],x['Manufacturer']),axis=1) 

然后我试图创建一个列表来搜索和过滤......

List=('Dell' or 'computer' or 'lenovo')
df=df[df['combine'].str.contains(List)]

但是,当我运行此代码时,我只获得与第一个值对应的行,Dell 因此代码不会搜索列表中的每个单词。

还有其他方法可以解决这个问题吗?

谢谢!

【问题讨论】:

    标签: python list filter pandas


    【解决方案1】:

    你可以使用isin:

    In [14]: df[df.isin(['Dell computer', 'Dell', 'computer', 'lenovo']).any(axis=1)]
    Out[14]: 
        Supplier ProductDescription Manufacturer
    0       Dell           computer         Dell
    1        NaN      Dell computer          NaN
    3  OfficeMax             lenovo       lenovo
    

    我添加了“戴尔计算机”选项。如果您希望以不同的方式输入名称,您可能希望在执行此操作之前对您的名称进行规范化。这只完全匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多