python在numpy字符串数组中查找字符串模式

Zan*_*nam 5 python string numpy

我有一个长度为100的字符串'A'的numpy数组,它们是不同大小的句子.它是字符串非numpy字符串

>>> type(A[0])
<type 'str'>
Run Code Online (Sandbox Code Playgroud)

我想在A中找到字符串的位置,其中包含某些类似'zzz'的模式.

我试过了

np.core.defchararray.find(A, 'zzz')
Run Code Online (Sandbox Code Playgroud)

给出错误:

TypeError: string operation on non-string array
Run Code Online (Sandbox Code Playgroud)

我假设我需要将A中的每个'str'更改为numpy字符串?

编辑:

我想在A中找到'zzz'外观的索引

wnn*_*maw 6

不需要对此有所了解,您可以通过列表理解和in运算符获取标记列表:

>>> import numpy as np
>>> lst = ["aaa","aazzz","zzz"]
>>> n = np.array(lst)
>>> [i for i,item in enumerate(n) if "zzz" in item]
[1, 2]
Run Code Online (Sandbox Code Playgroud)

请注意,这里数组的元素实际上是numpy字符串,但in运算符也适用于常规字符串,所以它没有实际意义.


hpa*_*ulj 5

这里的问题是字符串数组的性质。

如果我使数组如下:

In [362]: x=np.array(['one','two','three'])

In [363]: x
Out[363]: 
array(['one', 'two', 'three'], 
      dtype='<U5')

In [364]: type(x[0])
Out[364]: numpy.str_
Run Code Online (Sandbox Code Playgroud)

元素是特殊类型的字符串,隐式填充为 5 个字符(最长的 'np.char 方法适用于这种数组

In [365]: np.char.find(x,'one')
Out[365]: array([ 0, -1, -1])
Run Code Online (Sandbox Code Playgroud)

但是如果我创建一个包含字符串的对象数组,它会产生你的错误

In [366]: y=np.array(['one','two','three'],dtype=object)

In [367]: y
Out[367]: array(['one', 'two', 'three'], dtype=object)

In [368]: type(y[0])
Out[368]: str

In [369]: np.char.find(y,'one')
...
/usr/lib/python3/dist-packages/numpy/core/defchararray.py in find(a, sub, start, end)
...
TypeError: string operation on non-string array
Run Code Online (Sandbox Code Playgroud)

通常情况下,对象数组必须被视为一个列表。

In [370]: y
Out[370]: array(['one', 'two', 'three'], dtype=object)

In [371]: [i.find('one') for i in y]
Out[371]: [0, -1, -1]

In [372]: np.array([i.find('one') for i in y])
Out[372]: array([ 0, -1, -1])
Run Code Online (Sandbox Code Playgroud)

这些np.char方法很方便,但速度并不快。他们仍然必须遍历数组,将常规字符串操作应用于每个元素。