3

I have 3 2d-arrays, which I want to use to initialize a new 2d array. 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.

For example, I have these 3 2d-arrays:

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:

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?

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:

I should have used & operator instead of and (similar for '|' vs. or)

1

2 Answers 2

5

Given A, B, and C, you just have to convert them into numpy arrays and compute for D using:

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but this produces ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
hmm.. I rechecked everything using the sample that you gave and it worked. could you post a screenshot of your code?
you can also try D = np.logical_and(A > 4, np.logical_and(B < 5, C > 5)).astype(int).
Yeah, I rechecked with the sample and that works, but it doesn't work with my arrays hmm.. I will update the main post with more info on my real data.
Aah, I found the mistake. I used and instead of & operator
3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.