Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: extending arrays along a new axis?

Surely there must be a way to do this... I can't work it out.

I have a (9,4) array, and I want to repeat it along a 3rd axis 4096 times... So it becomes simply (9,4,4096), with each value from the 9,4 array simply repeated 4096 times down the new axis.

If my dubious 3D diagram makes sense (the diagonal is a z-axis)

4|   /off to 4096 3|  / 2| / 1|/_ _ _ _ _ _ _ _ _     1 2 3 4 5 6 7 8 9 

Cheers

EDIT: Just to clarify, the emphasis here is on the (9,4) array being REPEATED for each of the 4096 'rows' of the new axis. Imagine a cross-section - each original (9,4) array is one of those down the 4096 long cuboid.

like image 263
Duncan Tait Avatar asked Mar 01 '10 17:03

Duncan Tait


People also ask

How do I expand an array in NumPy?

To expand the shape of an array, use the numpy. expand_dims() method. Insert a new axis that will appear at the axis position in the expanded array shape. The function returns the View of the input array with the number of dimensions increased.

Is NumPy apply along axis fast?

The np. apply_along_axis() function seems to be very slow (no output after 15 mins).

How do I put two NumPy arrays together?

Use numpy.stack() function to join a sequence of arrays along a new axis. You pass a sequence of arrays that you want to join to the numpy. stack() function along with the axis.

How do you stack an array depth wise?

To stack masked arrays in sequence depth wise (along third axis), use the ma. dstack() method in Python Numpy. This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1).


2 Answers

Here is one way:

import scipy X = scipy.rand(9,4,1) Y = X.repeat(4096,2) 

If X is given to you as only (9,4), then

import scipy X = scipy.rand(9,4) Y = X.reshape(9,4,1).repeat(4096,2) 
like image 114
Steve Tjoa Avatar answered Sep 23 '22 11:09

Steve Tjoa


You can also rely on the broadcasting rules to repeat-fill a re-sized array:

import numpy X = numpy.random.rand(9,4) Y = numpy.resize(X,(4096,9,4)) 

If you don't like the axes ordered this way, you can then transpose:

Z = Y.transpose(1,2,0) 
like image 34
Paul Avatar answered Sep 23 '22 11:09

Paul