gpt4 book ai didi

python - 根据多个条件获取 NumPy 数组的连续元素组

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:45 24 4
gpt4 key购买 nike

我有 2 个 NumPy 数组如下:

import numpy as np
a = np.array([1, 4, 2, 6, 4, 4, 6, 2, 7, 6, 2, 8, 9, 3, 6, 3, 4, 4, 5, 8])
b = np.array([2, 8, 3, 9, 9, 9, 7, 5, 4, 8, 6, 5, 4, 4, 7, 2, 1, 1, 9, 9])

和2个常数:

c = 6
d = 3

基于 a previous question ,每次 a 中的元素小于 c 时,我都可以提取一个数组,连续 2 次或更多次:

array = np.append(a, -np.inf)  # padding so we don't lose last element
mask = array >= c # values to be removed
split_indices = np.where(mask)[0]
for subarray in np.split(array, split_indices + 1):
if len(subarray) > 2:
print(subarray[:-1])

哪个输出:

[1. 4. 2.]
[4. 4.]
[3. 4. 4. 5.]

现在,我想将我的条件更改为多个条件,其中,连续 2 次或更多次:

  1. a中的元素小于c,

  1. b 中的元素小于d

使用以下代码:

mask = ((a< c) & (b< d))

我知道我的条件(连续 2 次或更多次)在索引 151617 处仅满足 1 次。

现在我想提取满足我条件的索引对应的a的值。

根据链接答案,我试过:

a1= np.append(a, -np.inf)
a2=np.append(b, -np.inf) # padding so we don't lose last element
mask = ((a1< c) & (a2< d)) # values to be removed
split_indices = np.where(mask)[0]
for subarray in np.split(a, split_indices + 1):
if len(subarray) > 2:
print(subarray[:-1])

令人惊讶的是,返回一个不满足我的条件的数组...

[4 2 6 4 4 6 2 7 6 2 8 9 3 6]

我还尝试了 np.extract 如下:

np.extract((len(list(g))>=2 for i, g in ((a < c) & (b < d)) if i), a)

返回值 1 而不是数组 a 的值...

期望的输出数组应该是索引15,16,17中的一个对应值[3 4 4 ] 在数组 a 中。

有人能告诉我可以使用哪些 python 工具来提取满足我的多个条件的数组吗?

注意:这是我的问题的一个最小示例,在我的“现实生活”中,我需要连续 14 次或更多次找到满足我的条件的数组!

最佳答案

请注意,在您的 previous question 中当您在 array 中查找元素时小于 threshold , 你的 mask被定义为不是 mask = array < threshold但作为它的反面:mask = array >= threshold .这是因为它稍后用于获取将被删除的元素。

因此,在您的新示例中,您还必须获得掩码的倒数。而不是 mask = (a1 < c) & (a2 < d)你需要mask = ~((a1 < c) & (a2 < d)) :

a1= np.append(a, -np.inf)
a2 = np.append(b, -np.inf)
mask = ~((a1 < c) & (a2 < d))
split_indices = np.where(mask)[0]
for subarray in np.split(a, split_indices + 1):
if len(subarray) > 2:
print(subarray[:-1])

给出:

[3 4 4]

这是a的第15-17个元素.

关于python - 根据多个条件获取 NumPy 数组的连续元素组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56907118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com