可以按如下方式选择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
- indices = np.where(a>0.9)
我想要做的是能够在这样的元素选择中使用正则表达式.例如,如果我想从上面的b中选择与[Aab] regexp匹配的元素,我需要编写以下代码:
- regexp = '[Ab]'
- selection = np.array([bool(re.search(regexp,element)) for element in b])
这对我来说太过分了.有没有更短更优雅的方式来做到这一点?