Sebastian
Sebastian

Reputation: 754

How to map numpy arrays to one another?

I have two (A, B) boolean arrays of the same finite, but arbitrarily large, and only known at runtime shape and dimensions.

I want to calculate the value of a boolean function of corresponding elements in A and B and store them in C. At last I need a list of tuples where C is true.

How to get there?

I dont want to iterate over the single elements, because I dont know how many dimensions there are, there must be a better way.

>>> A = array([True, False, True, False, True, False]).reshape(2,3)
>>> B = array([True, True, False, True, True, False]).reshape(2,3)
>>> A == B
array([[ True, False, False],
       [False,  True,  True]], dtype=bool)

as wanted, but:

>>> A and B
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How do I get "A and B"?

I tried "map", "zip", "nditer" and searched for other methods unsuccessfully.

As for the things with the tuples, I need something like "argmax" for booleans, but didn't find anything either.

Do you know somethign, that might help?

Upvotes: 1

Views: 806

Answers (2)

dpinte
dpinte

Reputation: 432

You can also use the & operator:

In [5]: A & B

array([[ True, False, False],
       [False,  True, False]], dtype=bool)

The big win with the logical_and call is that you can use the out parameter:

In [6]: C = empty_like(A)

In [7]: logical_and(A, B, C)

array([[ True, False, False],
       [False,  True, False]], dtype=bool)

Upvotes: 3

Janne Karila
Janne Karila

Reputation: 25207

Yes, there is a function in NumPy:

numpy.logical_and(A,B)

Upvotes: 2

Related Questions