python - 将字符串操作应用于 numpy 数组?

标签 python numpy

是否有更好的方法将字符串操作应用到 ndarray 而不是迭代它们?我想使用“向量化”操作,但我只能想到使用 map(示例所示)或列表理解。

Arr = numpy.rec.fromrecords(zip(range(5),'as far as i know'.split()),
                            names='name, strings')

print ''.join(map(lambda x: x[0].upper()+'.',Arr['strings']))
=> A.F.A.I.K.

比如在R语言中,字符串操作也是向量化的:

> (string <- unlist(strsplit("as far as i know"," ")))
[1] "as"   "far"  "as"   "i"    "know"
> paste(sprintf("%s.",toupper(substr(string,1,1))),collapse="")
[1] "A.F.A.I.K."

最佳答案

是的,最近的 NumPy 有矢量化字符串操作,在 numpy.char模块。例如,当你想在一个字符串数组中找到所有以 B 开头的字符串时,那就是

>>> y = np.asarray("B-PER O O B-LOC I-LOC O B-ORG".split())
>>> y
array(['B-PER', 'O', 'O', 'B-LOC', 'I-LOC', 'O', 'B-ORG'], 
      dtype='|S5')
>>> np.char.startswith(y, 'B')
array([ True, False, False,  True, False, False,  True], dtype=bool)

关于python - 将字符串操作应用于 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8089940/

相关文章:

python - 遍历 numpy.ma 数组,忽略屏蔽值

python - Numpy 索引数组到元素数组

python - 类型 str 没有定义 __round__ 方法错误

python - 生成复制任意分布的随机数

python - 发送 key 不起作用 selenium webdriver python

python - 如何修复 Flask 上的 "KeyError: ' log_context' "

python - 如何将 JSON 字节串读入 pandas

python - python函数的可选参数字符串和数据框

python - python 中数据的多维缩放

python - 成功安装 NumPy,但无法使用 virtualenv 访问