2017-02-25 17 views
-2

我有字符串的列表如下:掉落行通過匹配子串列表

drop_list = [ "www.stackoverflow", "www.youtube."] 

我有一個熊貓數據幀df用柱,用名column_name1說,其可能或可能不包含drop_list中的子字符串。樣品DF如下:

columnname1 
------------ 
https://stackoverflow.com/python-pandas-drop-rows-string-match-from-list 
https://stackoverflow.com/deleting-dataframe-row-in-pandas-column-value 
https://textblob.readthedocs.io/en/dev/quickstart.html#create-a-textblob 
https://textblob.readthedocs.io/en/dev/ 
https://textblob.readthedocs.io/en/stackoverflow 
https://textblob.readthedocs.io/en/youtube 
https://www.youtube.com/watch?v=sHkjdkjsk 
https://www.youtube.com/watch?v=_jksjdkjklI 
https://www.youtube.com/watch?v=jkjskjkjkjkw 

所以,我想從DF,其中包含從drop_list子串刪除所有行。

如果我理解正確,如果drop_list是我想要匹配的確切值,那麼我可以根據此SO問題使用以下代碼。

df[~df['column_name1'].isin(to_drop)] 

或者使用str.contains方法在this回答表明,如果它只是一個價值

df[~df['column_name1'].str.contains("XYZ")] 

現在,如何既與方法相結合,刪除列?所需的輸出將丟棄包含計算器或從我的數據幀的YouTube任何行:

columnname1 
------------ 
https://textblob.readthedocs.io/en/dev/quickstart.html#create-a-textblob 
https://textblob.readthedocs.io/en/dev/ 
https://textblob.readthedocs.io/en/stackoverflow 
https://textblob.readthedocs.io/en/youtube 

如果我按原樣運行df = df[~df['col1'].str.contains('|'.join(to_drop))]to_drop,它保留了stackoverflow網址,但刪除了youtube網址。

如果我改變我的列表更通用如下 to_drop =「計算器」,「YouTube」的視頻]

它刪除

https://textblob.readthedocs.io/en/stackoverflow 
https://textblob.readthedocs.io/en/youtube 

因此,所有我試圖做的是刪除所有包含stackoverflow和youtube網址的行。我正在避免使用urlparse庫!

Here是MWE。

+1

請提供的樣品數據集和所希望的數據集 – MaxU

+1

'.str.contains('| '.join(to_drop))'可以用來檢查'to_drop'中的所有元素,但我不確定這是不是你問的。我認爲樣本也會很好。 – ayhan

+0

新增樣本數據集。 '''.str.contains('|'.join(to_drop))'''解決不了我相信。 – kingmakerking

回答

0

嘗試這種情況:

import re 

drp = [re.sub(r'www\.|\.$|\.com', '', x) for x in to_drop] 
df[~df.col1.str.extract(r'http[s]*://([^/]*).*', expand=False) 
    .str.contains('|'.join(drp))] 

收率:

                 col1 
2 https://textblob.readthedocs.io/en/dev/quickstart.html#create-a-textblob 
3         https://textblob.readthedocs.io/en/dev/ 
4       https://textblob.readthedocs.io/en/stackoverflow 
5        https://textblob.readthedocs.io/en/youtube 

說明:

In [38]: drp 
Out[38]: ['stackoverflow', 'youtube'] 

In [41]: df.col1.str.extract(r'http[s]*://([^/]*).*', expand=False) 
Out[41]: 
0   stackoverflow.com 
1   stackoverflow.com 
2 textblob.readthedocs.io 
3 textblob.readthedocs.io 
4 textblob.readthedocs.io 
5 textblob.readthedocs.io 
6   www.youtube.com 
7   www.youtube.com 
8   www.youtube.com 
Name: col1, dtype: object 

In [42]: df.col1.str.extract(r'http[s]*://([^/]*).*', expand=False).str.contains('|'.join(drp)) 
Out[42]: 
0  True 
1  True 
2 False 
3 False 
4 False 
5 False 
6  True 
7  True 
8  True 
Name: col1, dtype: bool