deepayan das
deepayan das

Reputation: 1657

How to perform row wise OR operation on a 2D numpy array?

I have a numpy array.

[[1, 0, 1],
  [1, 0, 0],
  [0, 0, 1]]

I want to perform rowise OR operation on it so that the resulting array looks like this:

[1, 0, 1]

Is there a straight forward way for doing this without implementing loops ? I will be very grateful if someone could suggest something. Thanks

Upvotes: 3

Views: 2523

Answers (2)

alkasm
alkasm

Reputation: 23062

If you'd prefer to stick with bitwise or (the | operator in Python is a bitwise or, whereas the or operator is the boolean or), you can use np.bitwise_or(). However, this only takes two arrays as input, so you can use Numpy's reduce() capabilities to combine all the subarrays in the array.

>>> a = np.array([[1, 0, 1],[1, 0, 0],[0, 0, 1]])
>>> np.bitwise_or.reduce(a, 0)
array([1, 0, 1])

I like how explicit this is, but the a.any() solution is common enough to not raise any eyebrows. The first argument for reduce is of course the array and the second is the axis you're reducing along. So you could also do it column-wise, if you preferred, or any other axis for that matter.

>>> a = np.array([[1, 0, 1],[1, 0, 0],[0, 0, 1]])
>>> np.bitwise_or.reduce(a, 1)
array([1, 1, 1])

Upvotes: 4

EdChum
EdChum

Reputation: 394469

You could do this by calling any to generate a boolean mask and then cast to int to convert the True and False to 1 and 0 respectively:

In[193]:
a.any(0).astype(int)

Out[193]: array([1, 0, 1])

The first param to any is the axis arg, here we can see the differences between axis 0 and 1:

In[194]:
a.any(0)

Out[194]: array([ True, False,  True], dtype=bool)

In[195]:
a.any(1)

Out[195]: array([ True,  True,  True], dtype=bool)

Upvotes: 4

Related Questions