搜索 return 与 pandas 匹配的子字符串的索引
Search and return index of matching substring with pandas
我想扩展所问的问题 here
上述问题的答案return判断对错。并且布尔值可用于对正确的值进行子集化。
但是,我想获取与子字符串匹配的搜索值。
例如,(借用上面的问题)
s = pd.Series(['cat','hat','dog','fog','pet'])
searchfor = ['og', 'at']
我想知道 'cat' 与 'at' 匹配,狗与 'og'
匹配
IIUC,您希望值反映 index searchfor
列表中与您的单词匹配的项目。您可以从修改 searchfor
对象开始 -
m = {'^.*{}.*$'.format(s) : str(i) for i, s in enumerate(searchfor)}
这是 <pattern : index>
映射的字典。现在,用 regex=True
-
调用 pd.Series.replace
s = s.replace(m, regex=True)
s[:] = np.where(s.str.isdigit(), pd.to_numeric(s, errors='coerce'), -1)
s
0 1
1 1
2 0
3 0
4 -1
dtype: int64
如果您想要按模式匹配的值列表,您需要 str.extract
+ groupby
+ apply
-
p = '(^.*({}).*$)'.format('|'.join(searchfor))
s.str.extract(p, expand=True)\
.groupby([1])[0]\
.apply(list)
1
at [cat, hat]
og [dog, fog]
Name: 0, dtype: object
这是通过使用 defaultdict
+ replace
最后我做到了..
d=dict(zip(searchfor,[""]*2))
s1=s.replace(d,regex=True)
import collections
d = collections.defaultdict(dict)
for x,y in zip(s1.index,s1):
d[x][y]=''
s.to_frame('a').T.replace(dict(d), regex=True).T.a
Out[765]:
0 at
1 at
2 og
3 og
4
Name: a, dtype: object
我想扩展所问的问题 here
上述问题的答案return判断对错。并且布尔值可用于对正确的值进行子集化。
但是,我想获取与子字符串匹配的搜索值。
例如,(借用上面的问题)
s = pd.Series(['cat','hat','dog','fog','pet'])
searchfor = ['og', 'at']
我想知道 'cat' 与 'at' 匹配,狗与 'og'
匹配IIUC,您希望值反映 index searchfor
列表中与您的单词匹配的项目。您可以从修改 searchfor
对象开始 -
m = {'^.*{}.*$'.format(s) : str(i) for i, s in enumerate(searchfor)}
这是 <pattern : index>
映射的字典。现在,用 regex=True
-
pd.Series.replace
s = s.replace(m, regex=True)
s[:] = np.where(s.str.isdigit(), pd.to_numeric(s, errors='coerce'), -1)
s
0 1
1 1
2 0
3 0
4 -1
dtype: int64
如果您想要按模式匹配的值列表,您需要 str.extract
+ groupby
+ apply
-
p = '(^.*({}).*$)'.format('|'.join(searchfor))
s.str.extract(p, expand=True)\
.groupby([1])[0]\
.apply(list)
1
at [cat, hat]
og [dog, fog]
Name: 0, dtype: object
这是通过使用 defaultdict
+ replace
最后我做到了..
d=dict(zip(searchfor,[""]*2))
s1=s.replace(d,regex=True)
import collections
d = collections.defaultdict(dict)
for x,y in zip(s1.index,s1):
d[x][y]=''
s.to_frame('a').T.replace(dict(d), regex=True).T.a
Out[765]:
0 at
1 at
2 og
3 og
4
Name: a, dtype: object