加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 使用正则表达式选择numpy数组中的元素

发布时间:2020-12-14 06:26:25 所属栏目:百科 来源:网络整理
导读:可以按如下方式选择numpy数组中的元素 a = np.random.rand(100)sel = a 0.5 #select elements that are greater than 0.5a[sel] = 0 #do something with the selectionb = np.array(list('abc abc abc'))b[b==a] = 'A' #convert all the a's to A's np.where
可以按如下方式选择numpy数组中的元素
a = np.random.rand(100)
sel = a > 0.5 #select elements that are greater than 0.5
a[sel] = 0 #do something with the selection

b = np.array(list('abc abc abc'))
b[b==a] = 'A' #convert all the a's to A's

np.where函数使用此属性来检索索引:

indices = np.where(a>0.9)

我想要做的是能够在这样的元素选择中使用正则表达式.例如,如果我想从上面的b中选择与[Aab] regexp匹配的元素,我需要编写以下代码:

regexp = '[Ab]'
selection = np.array([bool(re.search(regexp,element)) for element in b])

这对我来说太过分了.有没有更短更优雅的方式来做到这一点?

这里涉及一些设置,但除非numpy对我不知道的正则表达式有某种直接支持,否则这是最“numpytonic”的解决方案.它试图使数组迭代比标准python迭代更有效.
import numpy as np
import re

r = re.compile('[Ab]')
vmatch = np.vectorize(lambda x:bool(r.match(x)))

A = np.array(list('abc abc abc'))
sel = vmatch(A)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读