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

2024-04-27 09:35:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个长度为100的字符串a的numpy数组,它们是不同大小的句子。它是字符串而不是numpy字符串

>>> type(A[0])
<type 'str'>

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

我试过了

np.core.defchararray.find(A, 'zzz')

给出错误:

TypeError: string operation on non-string array

我想我需要把字符串中的每个str都改成numpy?

编辑:

我想在一个


Tags: 字符串corenumpystringtype错误np模式
3条回答

你可以试试这个:

np.core.defchararray.find(A.astype(str), 'zzz')

无需对此感到好奇,您可以通过列表理解和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]

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

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

如果我把数组设置成:

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_

元素是一种特殊的字符串,隐式填充为5个字符(最长的,np.char方法处理这种数组

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

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

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

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

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])

np.char方法很方便,但速度并不快。它们仍然需要遍历数组,对每个元素应用常规的字符串操作。

相关问题 更多 >