簡體   English   中英

創建Or列表,然后使用該列表過濾數據框Pandas / Python

[英]Creating a list of Or's and then filtering dataframe using that list Pandas/Python

我有一個數據框,如下所示:

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

我想通過包含某些單詞但沒有重復計算的行來過濾出此數據框。 因此,從本質上講,我想保留包含“ Dell”或“計算機”或“ 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相對應的行,因此該代碼不會在列表中搜索每個單詞。

還有其他解決方法嗎?

謝謝!

您可以使用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

我添加了“戴爾計算機”選項。 如果您希望輸入不同的名稱,則可能需要先對名稱進行正則化。 這僅完全匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM