[英]Efficiently drop rows in a Pandas Dataframe, where you need to tokenize the text of a column first in order to pass a conditional statement
[英]Tokenize text in Pandas dataframe
我有一個Pandas DataFrame,其中包含從外部來源收集的腳本。 列text_content
包含腳本內容。 最長的腳本包含85.617個字符。
一個樣本可以給你一個想法:
腳本包含表名和其他有用的信息。 當前,數據幀已寫入SQLite數據庫表,然后可以使用臨時SQL語句進行搜索(並分發給更大的人群)。
一個常見的用例是我們將有一個表名列表,並且想知道它們出現的腳本。 如果我們需要在SQL中執行此操作,則將需要我們使用LIKE
運算符執行通配符搜索,這有點糟於性能。
因此,我想在腳本仍在DataFrame中時從腳本中提取單詞 ,從而得到兩列表格,每一行包括:
每個腳本將導致許多行(取決於匹配項的數量)。
到目前為止,我編寫此代碼是為了從腳本中提取單詞:
DataFrame(df[df.text_type == 'DISCRIPT']
.dropna(subset=['text_content'])
.apply(lambda x: re.findall('([a-zA-Z]\w+)', x['text_content']), axis=1)
.tolist())
結果:
到現在為止還挺好 (?)。
我還需要執行兩個步驟,但這里有些困難。
我可以使用T
來轉置DataFrame,結合使用replace()
和預定義的關鍵字列表(用NA值替換它們),最后使用dropna()
將列表縮短為僅關鍵字。 但是,我不確定這是否是最佳方法。
非常感謝您的意見和建議!
IIUC你可以嘗試添加index=df.index
到df2
構造,然后通過重塑stack
和過濾的isin
:
print df
text_content text_name text_type
1614 CHECK FOR LOCK STATUS CACHETABLEDB TEXT DISCRIPT
1615 CHECK FOR LOCK STATUS CACHETABLEDB TEXT DISCRIPT
df2 = pd.DataFrame(df[df.text_type == 'DISCRIPT']
.dropna(subset=['text_content'])
.apply(lambda x: re.findall('([a-zA-Z]\w+)', x['text_content']), axis=1)
.tolist(), index=df.index)
print df2
0 1 2 3 4
1614 CHECK FOR LOCK STATUS CACHETABLEDB
1615 CHECK FOR LOCK STATUS CACHETABLEDB
#reshape all rows to column
df2 = df2.stack().reset_index(level=0)
df2.columns = ['id', 'words']
L = ['CACHETABLEDB','STATUS']
#remove reserved words
df2 = df2.loc[~df2.words.isin(L)].reset_index(drop=True)
print df2
id words
0 1614 CHECK
1 1614 FOR
2 1614 LOCK
3 1615 CHECK
4 1615 FOR
5 1615 LOCK
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.