[英]Populating Pandas DataFrame column based on dictionary of regex
我有一個如下數據框:
GE GO
1 AD Weiss
2 KI Ruby
3 OH Port
4 ER Rose
5 KI Rose
6 JJ Weiss
7 OH 7UP
8 AD 7UP
9 OP Coke
10 JJ Stout
我正在嘗試根據GO
列的值添加一列。 我正在考慮使用字典,但我需要使用正則表達式來識別我的實際案例中的部分匹配。 例如:
Dic={'Weiss|\wuby|Sto\w+':'Beer', 'Port|Rose':'Wine','\dUP|Coke':'Soda'}
這會給
GE GO OUT
1 AD Weiss Beer
2 KI Ruby Beer
3 OH Port Wine
4 ER Rose Wine
5 KI Rose Wine
6 JJ Weiss Beer
7 OH 7UP Soda
8 AD 7UP Soda
9 OP Coke Soda
10 JJ Stout Beer
lambda函數在這里工作嗎? 我怎么把它變成正則表達式? 提前致謝!
你可以這樣做:
In [253]: df['OUT'] = df[['GO']].replace({'GO':Dic}, regex=True)
In [254]: df
Out[254]:
GE GO OUT
1 AD Weiss Beer
2 KI Ruby Beer
3 OH Port Wine
4 ER Rose Wine
5 KI Rose Wine
6 JJ Weiss Beer
7 OH 7UP Soda
8 AD 7UP Soda
9 OP Coke Soda
10 JJ Stout Beer
Intereseting觀察 - 在較舊的Pandas版本中,與DataFrame.replace()
和Series.str.replace()
方法相比, Series.map()
方法幾乎總是更快。 它在Pandas 0.19.2中變得更好:
In [267]: df = pd.concat([df] * 10**4, ignore_index=True)
In [268]: %timeit df.GO.map(lambda x: next(Dic[k] for k in Dic if re.search(k, x)))
1 loop, best of 3: 1.57 s per loop
In [269]: %timeit df[['GO']].replace({'GO':Dic}, regex=True)
1 loop, best of 3: 895 ms per loop
In [270]: %timeit df.GO.replace(Dic, regex=True)
1 loop, best of 3: 876 ms per loop
In [271]: df.shape
Out[271]: (100000, 2)
一種選擇是在GO
列上使用帶有map
的re
模塊:
import re
df['OUT'] = df.GO.map(lambda x: next(Dic[k] for k in Dic if re.search(k, x)))
df
如果模式都不匹配,則會引發錯誤。 如果存在字符串與任何模式不匹配的情況,您可以編寫自定義函數來捕獲異常並返回None:
import re
def findCat(x):
try:
return next(Dic[k] for k in Dic if re.search(k, x))
except:
return None
df['OUT'] = df.GO.map(findCat)
df
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.