多行 numpy where() 条件

Multi-line numpy where() condition

各位, 为了避免 for 循环,我正在研究一种基于向量的方法来执行以下操作:

Array_1 的浮点值范围从 -3.0 到 3.0,并且在这些极端值之间随机游走。

我想创建 Array_2 是这样的:

Array_2 = np.where((Array_1[row] > 2) & (Array_1[row-1] < 2),1,0)

如何在我的 np.where() 条件下完成此操作? 最终我想避免 for 循环。

有什么想法吗?

您实际上不需要在输入上使用 np.where, you apply np.roll 来构造一个辅助数组,它可以让您访问带有偏移量的原始数组

>>> x = np.random.uniform(-3, 3, 20)
array([ 0.87457789,  2.78372382,  2.99091498,  1.13015817,  2.08503683,
        1.48561846, -1.30544443, -1.34806256,  0.46013052,  1.71623744,
       -1.11043827, -0.14515713,  2.81997195,  0.62134152, -1.95262578,
       -0.93686073,  0.56367685,  1.96501996,  0.59958956,  2.6594141 ])

滚动 x 偏移 1:

>>> (x > 2)*(np.roll(x, 1) < 2)
array([False,  True, False, False,  True, False, False, 
       False, False, False, False, False,  True, False, 
       False, False, False, False, False,  True])

如果您想将结果数组强制转换为整数或浮点数:

>>> (x > 2)*(np.roll(x, 1) < 2)*1
array([0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1])