Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling an array with arrays or vectors in python using numpy without a loop

I'm trying to find a way to fill an array with rows of values. It's much easier to express my desired output with an example. Given the input of an N x M matrix, array1,

array1 = np.array([[2, 3, 4],
[4, 8, 3],
[7, 6, 3]])

I would like to output an array of arrays in which each row is an N x N consisting of the values from the respective row. The output would be

[[[2, 3, 4],
  [2, 3, 4],
  [2, 3, 4]],
 [[4, 8, 3],
  [4, 8, 3],
  [4, 8, 3]],
 [[7, 6, 3],
  [7, 6, 3],
  [7, 6, 3]]]
like image 289
Bryan Charlie Avatar asked Feb 19 '26 20:02

Bryan Charlie


2 Answers

You can reshape the array from 2d to 3d, then use numpy.repeat() along the desired axis:

np.repeat(array1[:, None, :], 3, axis=1)

#array([[[2, 3, 4],
#        [2, 3, 4],
#        [2, 3, 4]],

#       [[4, 8, 3],
#        [4, 8, 3],
#        [4, 8, 3]],

#       [[7, 6, 3],
#        [7, 6, 3],
#        [7, 6, 3]]])

Or equivalently you can use numpy.tile:

np.tile(array1[:, None, :], (1,3,1))
like image 58
Psidom Avatar answered Feb 22 '26 10:02

Psidom


Another solution which is sometimes useful is the following

out = np.empty((3,3,3), dtype=array1.dtype)
out[...] = array1[:, None, :]
like image 44
Paul Panzer Avatar answered Feb 22 '26 09:02

Paul Panzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!