3

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]]]

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

Comments

1

Another solution which is sometimes useful is the following

out = np.empty((3,3,3), dtype=array1.dtype)
out[...] = array1[:, None, :]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.