简体   繁体   English

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

[英]Create new 2d numpy array based on threshold values from other arrays

I have 3 2d-arrays, which I want to use to initialize a new 2d array. 我有3个2d阵列,我想用它来初始化一个新的2d阵列。 The new 2d-array should be populated with either a 0 or 1 in position (x,y) depending on the values in the (x,y) positions of the other 3 arrays. 新的2d阵列应填充位置(x,y)的0或1,具体取决于其他3个阵列的(x,y)位置的值。

For example, I have these 3 2d-arrays: 例如,我有这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]]

And a logic function: 和逻辑功能:

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

This should create the 2d-array: 这应该创建2d数组:

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

Now I can do this with 2 for loops, but I was wondering if there is a faster numpy way? 现在我可以使用2 for循环来做到这一点,但我想知道是否有更快的numpy方式?

EDIT : 编辑

Here is a sample of my real code: 以下是我的真实代码示例:

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

But I get this error: 但我得到这个错误:

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 : 编辑2

I should have used & operator instead of and (similar for '|' vs. or ) 我应该使用&运算符而不是and (类似于'|'vs. or

Given A, B, and C, you just have to convert them into numpy arrays and compute for D using: 给定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)

Try: 尝试:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM