根据其他数组的阈值创建新的2d numpy数组

时间:2016-03-30 15:12:50

标签: python arrays numpy

我有3个2d阵列,我想用它来初始化一个新的2d阵列。 新的2d数组应填充0或1的位置(x,y),具体取决于其他3个数组的(x,y)位置的值。

例如,我有这3个2d阵列:

A = [[2, 3, 6],    B = [[5, 9, 0],    C = [[2, 7, 6],
     [9, 8, 3],         [2, 4, 3],         [2, 1, 6],
     [1, 0, 5]]         [4, 5, 1]]         [4, 6, 8]]

逻辑功能:

D = (A > 4 && B < 5 && C > 5)

这应该创建2d阵列:

D = [[0, 0, 1], 
     [0, 0, 0],
     [0, 0, 1]]

现在我可以用2 for循环来做这个,但我想知道是否有更快的numpy方式?

编辑

以下是我的真实代码示例:

val_max = 10000
a = np.asarray(array_a)
b = np.asarray(array_b)
d = ((a >= val_max) and (b >= val_max)).astype(int)

但是我收到了这个错误:

Traceback (most recent call last):
  File "analyze.py", line 70, in <module>
    d = ((a >= val_max) and (b >= val_max)).astype(int)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

EDIT2

我应该使用&运算符代替and(类似于'|'与or

2 个答案:

答案 0 :(得分:5)

给定A,B和C,您只需将它们转换为numpy数组并使用以下方法计算D:

import numpy as np

A = np.asarray(A)
B = np.asarray(B)
C = np.asarray(C)

D = ((A > 4) & (B < 5) & (C > 5)).astype(int)

答案 1 :(得分:3)

尝试:

import numpy as np
A = np.asarray(A)
B = np.asarray(B)
C = np.asarray(C)
D = ((A > 4) & (B < 5) & (C > 5)).astype(int)
相关问题