Is there a more vectorial way to execute numpy.outer along the axis?

>>> x = np.array([['a0', 'a1'],['b0','b1']]) >>> y = np.array([['x0', 'x1'],['y0','y1']]) >>> iterable = [np.outer(x[i],y[i]) for i in xrange(x.shape[0])] >>> elbareti = np.asarray(iterable) >>> elbareti array([[[ 'a0'*'x0', 'a0'*'x1' ], [ 'a1'*'x0', 'a1'*'x1' ]], [[ 'b0'*'y0', 'b0'*'y1' ], [ 'b1'*'y0', 'b1'*'y1' ]]]) 

Since I plan to work with large arrays, are there any other versions similar to them? I feel that the answer is right under my nose, and I think it has something to do with reduce , but the numpy version only works with ufunc s, not functions. Even a hint would be greatly appreciated.

Thanks in advance.

+6
source share
1 answer

Is this what you are looking for?

 x = np.array([[1,2], [3,4]]) y = np.array([[5,6], [7,8]]) x[:,:,np.newaxis] * y[:,np.newaxis,:] array([[[ 5, 6], [10, 12]], [[21, 24], [28, 32]]]) 

EDIT:

Btw, it’s always useful to look at the implementation. Helps to understand "magic." np.outer looks like this:

 return a.ravel()[:,newaxis]*b.ravel()[newaxis,:] 

It’s easy from here.

In addition, in your question you have:

 [np.outer(x[i],y[i]) for i in xrange(x.shape[0])] 

Better written as:

 [np.outer(xx,yy) for xx,yy in izip(x,y)] 
+8
source

Source: https://habr.com/ru/post/944781/


All Articles