我需要在pandas数据格式,以便特定的字符串列至少包含一个提供的子字符串列表中的一个。子字符串可能具有不寻常的/正则字符。比较不应涉及regex,而且不区分大小写。例如:lst = ['kdSj;af-!?', 'aBC+dsfa?\-', 'sdKaJg|dksaf-*']我现在用的口罩是这样的:mask = np.logical_or.reduce([df[col].str.contains(i, regex=False, case=False) for i in lst])df = df[mask]我的数据很大(~1mio行)和lst长度是100。有没有更有效的方法?例如,如果lst,我们就不必测试该行的任何后续字符串。熊猫对串联多个子串的过滤
3 回答

FFIVE
TA贡献1797条经验 获得超6个赞
re.escape
:
>>> import re>>> esc_lst = [re.escape(s) for s in lst]
|
>>> pattern = '|'.join(esc_lst)
df[col].str.contains(pattern, case=False)
from random import randint, seed seed(321)# 100 substrings of 5 characterslst = [''.join([chr(randint(0, 256)) for _ in range(5)]) for _ in range(100)]# 50000 strings of 20 charactersstrings = [''.join([chr(randint(0, 256)) for _ in range(20)]) for _ in range(50000)]col = pd.Series(strings)esc_lst = [re.escape(s) for s in lst]pattern = '|'.join(esc_lst)
%timeit col.str.contains(pattern, case=False)1 loop, best of 3: 981 ms per loop

智慧大石
TA贡献1946条经验 获得超3个赞
使用 更简单的例子&忽略案例(大写或小写)
过滤和获取二进制向量:
pd.Series
, v
re
:
import re
v=pd.Series(['cAt','dog','the rat','mouse','froG'])[Out]:0 cAt1 dog2 the rat3 mouse4 froG
pattern
pattern='at|Og'
v_binary=[1]*len(v)
s
True
v
pattern
False
s=v.str.contains(pattern, flags=re.IGNORECASE, regex=True)
v_binary
*s
:
v_binary*s[Out]0 11 12 13 04 1
添加回答
举报
0/150
提交
取消