繁体   English   中英

如何在 numpy 字符串数组中查找 substring 的所有出现

[英]How to find all occurences of a substring in a numpy string array

我试图在 numpy 字符串数组中查找 substring 的所有出现。 比方说:

myArray = np.array(['Time', 'utc_sec', 'UTC_day', 'Utc_Hour'])
sub = 'utc'

它应该不区分大小写,因此该方法应该返回 [1,2,3]。

使用np.char.lowernp.char.find矢量化方法

import numpy as np
myArray = np.array(['Time', 'utc_sec', 'UTC_day', 'Utc_Hour'])
res = np.where(np.char.find(np.char.lower(myArray), 'utc') > -1)[0]
print(res)

Output

[1 2 3]

这个想法是使用np.char.lower使np.char.find不区分大小写,然后使用np.where获取包含子字符串的索引。

您可以使用if sub in string来检查它。

import numpy as np

myArray = np.array(['Time', 'utc_sec', 'UTC_day', 'Utc_Hour'])
sub = 'utc'

count = 0
found = []
for item in myArray:
    if sub in item.lower():
        count += 1
        found.append(count)

print(found)

output:

[1, 2, 3]

我们可以使用列表comprehension来获得正确的索引:

occ = [i for i in range(len(myArray)) if 'utc' in myArray[i].lower()]

Output

>>> print(occ)
... [1, 2, 3]

让我们从这个问题做一个一般性的使用:我们将设置一个 function 返回numpy string arrayany字符的出现索引。

get_occ_idx(sub, np_array):
    """ Occurences index of substring in a numpy string array
    """
    
    assert sub.islower(), f"Your substring '{sub}' must be lower case (should be : {sub.lower()})"
    assert all(isinstance(x, str)==False for x in np_array), "All items in the array must be strings"
    assert all(sub in x.lower() for x in np_array), f"There is no occurence of substring :'{sub}'"
    
    occ = [i for i in range(len(np_array)) if sub in np_array[i].lower()]
    
    return occ

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM