這個問題在這里已經有了答案: 如何從資料框列中提取與串列的完全匹配? (2 個回答) 11 小時前關閉。
這是我的示例代碼:
import pandas as pd
df = pd.DataFrame({'A':
['btcrr',
'You have crypto here',
'coinbase.com was there ',
'hotwalletint']
})
regex = r"(^|\W)(?:btc|crypto|coinbase|hotwallet)[^A-Za-z0-9]"
tagged_df = df[df['A'].str.contains(regex, na=False, regex=True, case=False)]
的輸出tagged_df:
A
1 You have crypto here
2 coinbase.com was there
在這種情況下,僅當它與我提供的正則運算式匹配時才會回傳。但我希望熊貓回傳匹配的關鍵字。我期待這樣的事情回來tagged_df
的預期輸出tagged_df:
A
1 crypto
2 coinbase.com
如果熊貓沒有能力,請建議可以解決這種情況的替代方案。
uj5u.com熱心網友回復:
使用pandas.Series.str.extract(). 對于常規 expession 中的每個捕獲組(非捕獲組只是一個?:開頭的組,例如(?:abc)),將創建一個新列,其中包含該組的匹配值,對于該行。您還可以添加?P<your_name>到捕獲組的最開頭以命名與該組關聯的輸出列:
new_df = df['A'].str.extract(r'(?:^|\W)(?P<A>btc|crypto|coinbase|hotwallet)[^A-Za-z0-9]')
輸出:
>>> new_df
A
0 NaN
1 crypto
2 coinbase
3 NaN
>>> new_df.dropna()
A
1 crypto
2 coinbase
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376273.html
上一篇:Pandas:從較小的資料幀中減去一個資料幀:行外重新開始
下一篇:迭代資料框進行計算
