【问题标题】:python find string pattern in numpy array of stringspython在numpy字符串数组中查找字符串模式
【发布时间】:2016-10-02 15:46:44
【问题描述】:

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

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

我想在 A 中找到包含特定模式(如 'zzz')的字符串的位置。

我试过了

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

给出错误:

TypeError: string operation on non-string array

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

编辑:

我想在A中找到'zzz'出现的索引

【问题讨论】:

  • 找到它们后你想做什么?拆分它们?获取索引?
  • 为什么不只是[s.find(pattern) for s in A],然后您将在每个字符串中获得该模式第一次出现的索引(如果未找到该模式,则为-1)

标签: python string numpy


【解决方案1】:

无需花哨,您可以通过列表理解和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 运算符也适用于常规字符串,所以没有实际意义。

【讨论】:

    【解决方案2】:

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

    如果我将数组设为:

    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 方法很方便,但速度并不快。他们仍然需要遍历数组,对每个元素应用常规的字符串操作。

    【讨论】:

      【解决方案3】:

      你可以试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-06
        • 1970-01-01
        • 2020-06-19
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 2017-09-04
        • 2021-08-13
        相关资源
        最近更新 更多