user8371266
user8371266

Reputation:

NumPy - How would I vectorize this operation?

I need to take an array of dimension (M, 4) and subtract elements to return an array of (M, 2).

For example:

[[1, 2, 3, 4],
 [5, 6, 7, 8]]

# to

[[2, 2],
 [2, 2]]

What I've tried was the following:

subs = a[..., 2] - a[..., 0], a[..., 3] - a[..., 1]

But that returns in the manner of 2 arrays with dimension (M,).

Upvotes: 1

Views: 40

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477641

You can make views of your array, and then subtract the two views, like:

a[:,2:] - a[:,:2]

For example for some sample input:

>>> a
array([[5, 2, 9, 2],
       [9, 9, 7, 9]])
>>> a[:,2:] - a[:,:2]
array([[ 4,  0],
       [-2,  0]])

Upvotes: 3

Related Questions