python - 在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 窗口。有没有人可以轻松解决我的问题?我觉得我错过了一些非常明显的东西。
解决方案
推荐阅读
- python-3.x - 与多种数据类型(字符串、整数、浮点数等)的向量相似度?
- java - 如何在 Android 中减小 PDF Reader 的 APK 大小?- 爪哇
- c++ - 当构造函数风格的强制转换表现得像旧风格的强制转换时,gcc 会发出警告吗?
- google-earth-engine - 特征集合中每个特征的 ImageCollection.size()
- java - 如何在 iframe 中更改加载消息的方向或将 iframe 自动滚动到底部
- android-studio - Android Studio 北极狐将 testRunner 设置为 GRADLE 而不是 PLATFORM
- jquery - Asp.Net Core-Validation 并使用 Ajax 提交表单?
- angular - 在订阅中编辑后未定义的属性
- java - 如何设置点的坐标?
- angular - 从“css-loader!./test.css”导入测试返回字符串