簡體   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