Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise OR along one axis of a NumPy array

Tags:

numpy

For a given NumPy array, it is easy to perform a "normal" sum along one dimension. For example:

X = np.array([[1, 0, 0], [0, 2, 2], [0, 0, 3]])
X.sum(0)
    =array([1, 2, 5])
X.sum(1)
    =array([1, 4, 3])

Instead, is there an "efficient" way of computing the bitwise OR along one dimension of an array similarly? Something like the following, except without requiring for-loops or nested function calls.

Example: bitwise OR along zeroeth dimension as I currently am doing it:

np.bitwise_or(np.bitwise_or(X[:,0],X[:,1]),X[:,2])
    =array([1, 2, 3])

What I would like:

X.bitwise_sum(0)
    =array([1, 2, 3])
like image 492
Robert L. Avatar asked Dec 02 '16 21:12

Robert L.


People also ask

What is the 1 axis in NumPy?

Axis 1 is the direction along the columns In a multi-dimensional NumPy array, axis 1 is the second axis. When we're talking about 2-d and multi-dimensional arrays, axis 1 is the axis that runs horizontally across the columns.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

What is c_ in NumPy?

c_ = <numpy.lib.index_tricks.CClass object> Translates slice objects to concatenation along the second axis. This is short-hand for np. r_['-1,2,0', index expression] , which is useful because of its common occurrence.


1 Answers

numpy.bitwise_or.reduce(X, axis=whichever_one_you_wanted)

Use the reduce method of the numpy.bitwise_or ufunc.

like image 97
user2357112 supports Monica Avatar answered Sep 28 '22 07:09

user2357112 supports Monica