首页 > 解决方案 > 在numpy中索引多个范围

问题描述

我知道这个问题以不同的变体多次出现,但我找不到任何与我的问题真正匹配的东西。

总体思路:我有一个事件 ID 列表。我通过一个数组来查找事件 ID 发生的第一次和最后一次。first_time - 3然后我使用这些索引来检查在to范围内的另一个数组中的所有元素是否都是 NaN last_time + 3。最后,我计算了该范围内的所有元素在第二个数组中为 NaN 的频率。

counter=0
for event_ID in list_of_event_IDs:
    beginning_index, ending index = find_event_indices(some_array,event_ID) # +-3 is already added by this function
    if np.all(is_element_from_another_array_nan[beginning_index:ending_index]):
        counter += 1

这显然会导致对is_element_from_another_array_nan. 一旦我知道索引范围,我的想法是一次性完成所有这些调用。为此,我创建了一个包含索引的数组数组:

indices_array = np.zeros(len(list_of_event_IDs), 2), dtype=int)

for row, event_ID in enumerate(list_of_event_IDs):
    indices_array[row, :] = find_event_indices(some_array,event_ID)

indices_array=array([[  34,   40],
                     [  49,   55],
                     [  83,   89],
                     [ 765,  775],
                      ............

is_element_from_another_array_nan=array([ True,  True,  True, ...,  True,  True,  True])

我的想法是使用类似的东西 counter = np.sum(np.all(is_element_from_another_array_nan[indices_array], axis=1)),但这只会检查明确给出的索引,indices_array而不是它们之间的范围。我可以通过一个包含明确范围的数组来规避整个问题

indices=array([[34,35,36,37,38,39,40],
               [49,50,51,52,53,54,55],
                ........

这里的问题是数组内的数组将包含不同数量的元素,因此我不能使用np.zeros. 我可以通过使用列表而不是 numpy 数组来避免这种情况,但我觉得我错过了一些明显的东西。
我也不能这样做,np.all((some_array==event_ID) & is_element_from_another_array_nan)因为这会忽略我的 +-3 窗口。有没有人可以轻松解决我的问题?我觉得我错过了一些非常明显的东西。

标签: pythonarraysnumpyindexingrange

解决方案


推荐阅读