gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:36:11 25 4
gpt4 key购买 nike

可以如下选择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 = '[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)

关于regex - 使用正则表达式选择 numpy 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6595759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com