NumPy array extension over extra size

What is the easiest way to expand a given NumPy array over an extra size?

For example, suppose that

>>> np.arange(4) array([0, 1, 2, 3]) >>> _.shape (4,) >>> expand(np.arange(4), 0, 6) array([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]) >>> _.shape (6, 4) 

or this one is a bit more complicated:

 >>> np.eye(2) array([[ 1., 0.], [ 0., 1.]]) >>> _.shape (2, 2) >>> expand(np.eye(2), 0, 3) array([[[ 1., 0.], [ 0., 1.]], [[ 1., 0.], [ 0., 1.]], [[ 1., 0.], [ 0., 1.]]]) >>> _.shape (3, 2, 2) 
+6
source share
2 answers

I would recommend np.tile .

 >>> a=np.arange(4) >>> a array([0, 1, 2, 3]) >>> np.tile(a,(6,1)) array([[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]) >>> b= np.eye(2) >>> b array([[ 1., 0.], [ 0., 1.]]) >>> np.tile(b,(3,1,1)) array([[[ 1., 0.], [ 0., 1.]], [[ 1., 0.], [ 0., 1.]], [[ 1., 0.], [ 0., 1.]]]) 

Extending in many dimensions is also quite simple:

 >>> np.tile(b,(2,2,2)) array([[[ 1., 0., 1., 0.], [ 0., 1., 0., 1.], [ 1., 0., 1., 0.], [ 0., 1., 0., 1.]], [[ 1., 0., 1., 0.], [ 0., 1., 0., 1.], [ 1., 0., 1., 0.], [ 0., 1., 0., 1.]]]) 
+5
source

I think modifying the steps of an array makes writing expand easier:

 def expand(arr, axis, length): new_shape = list(arr.shape) new_shape.insert(axis, length) new_strides = list(arr.strides) new_strides.insert(axis, 0) return np.lib.stride_tricks.as_strided(arr, new_shape, new_strides) 

The function returns a representation of the original array that does not require additional memory.

The stride corresponding to the new axis is 0, so no matter what the index for these axis values ​​remains the same, you need behavior.

+1
source

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


All Articles