如果任何列包含关键字之一,则删除行

时间:2019-09-14 08:24:37

标签: python pandas dataframe python-3.7

我想删除任何列包含关键字之一的行

use SoftDeletes;
    protected $fillable = [
        'product_name', 'quantity', 'description' ,'supplier_id', 'price',
    ];

  public function supplier()
    {
        return $this->hasOne('App\Supplier');
    }
}

df之前:

keywords=['Nokia' , 'Asus']

data = [['Nokia', 'AB123','broken'], ['iPhone', 'DF747','battery'], ['Acer', 'KH298','exchanged for a nokia'], ['Blackberry', 'jj091','exchanged for a Asus']] 
df = pd.DataFrame(data, columns = ['Brand', 'ID', 'Description']) 

df之后:

Brand      | ID    |  Description
----------------------------------------
Nokia      | AB123 | broken
iPhone     | DF747 | battery
Acer       | KH298 | exchanged for a nokia
Blackberry | jj091 | exchanged for a Asus

我该如何实现?

2 个答案:

答案 0 :(得分:3)

您可以将所有列与0+连接在一起,然后通过Series.str.contains创建掩码,并使用apply为正则表达式|连接值:

OR

或者:

df = df[~(df['Brand']+df['ID']+df['Description']).str.contains('|'.join(keywords))]

如果需要区分大小写,请添加df = df[~df.apply(' '.join, 1).str.contains('|'.join(keywords))] print (df) Brand ID Description 1 iPhone DF747 battery 2 Acer KH298 exchanged for a nokia 参数:

case

答案 1 :(得分:1)

SELECT a.message_id, a.sent_from, a.sent_to, a.message, a.seen, 
       users.username, users.user_image, 
       b.unread_messages 
FROM messages a
  INNER JOIN 
  (SELECT sent_from, 
          max(message_id) AS maxid,
          COUNT(CASE WHEN seen = 'NO' THEN 1 ELSE NULL END) AS unread_messages 
   FROM messages 
   GROUP BY sent_from, sent_to) AS b ON a.message_id = b.maxid
INNER JOIN users ON users.user_id = a.sent_from
WHERE a.sent_to = 5

df = df[~(df.stack().str.contains('|'.join(keywords)).any(level=0))]

输出

df = df[~(df.astype(str).sum(axis=1).str.contains('|'.join(keywords)))]