使用正则表达式选择numpy数组中的元素 [英] Selecting elements in numpy array using regular expressions

查看:136
本文介绍了使用正则表达式选择numpy数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以按以下方式选择numpy数组中的元素

One may select elements in numpy arrays as follows

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函数使用此属性来检索索引:

This property is used by the np.where function to retrive indices:

indices = np.where(a>0.9)

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

What I would like to do is to be able to use regular expressions in such element selection. For example, if I want to select elements from b above that match the [Aab] regexp, I need to write the following code:

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

这对我来说太麻烦了.有没有更短,更优雅的方法来做到这一点?

This looks too verbouse for me. Is there any shorter and more elegant way to do this?

推荐答案

这里涉及到一些设置,但是除非numpy对我不了解的正则表达式提供某种直接支持,否则这是最"numpytonic"的"解决方案.它试图使数组上的迭代比标准python迭代更有效率.

There's some setup involved here, but unless numpy has some kind of direct support for regular expressions that I don't know about, then this is the most "numpytonic" solution. It tries to make iteration over the array more efficient than standard python iteration.

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)

这篇关于使用正则表达式选择numpy数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆