是否有更好的方法将字符串操作应用到 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/