2

Quite straightforward question, I have the following array:

x = np.array([1, 2, 3, 4, 5, 6, 7, 8])

I want to repeat this array over columns, having something like this:

array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4],
       [5, 5, 5],
       [6, 6, 6],
       [7, 7, 7],
       [8, 8, 8]])

So, in order to do so I have been trying:

repeat_x = np.repeat(x, 3, axis = 1)

However, I get the following error:

AxisError: axis 1 is out of bounds for array of dimension 1

So, is there a way/trick to achieve my goal without having to use any sort of reshape?

2

2 Answers 2

4

Try this code:

np.array([x] * 3).T

Here 3 is the number of times you want to repeat those values

0

To do it purely in numpy without resorting back to python lists you need to use expand_dims followed by a transpose or use reshape to convert the vector into a matrix before using repeat.

x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# array([1, 2, 3, 4, 5, 6, 7, 8])

x = x.reshape(-1, 1)
# array([[1],
#   [2],
#   [3],
#   [4],
#   [5],
#   [6],
#   [7],
#   [8]])

np.repeat(x.reshape(-1, 1), 3, 1)
# array([[1, 1, 1],
#    [2, 2, 2],
#    [3, 3, 3],
#    [4, 4, 4],
#    [5, 5, 5],
#    [6, 6, 6],
#    [7, 7, 7],
#    [8, 8, 8]])

Using expand dims and a transpose will be like

np.repeat(np.expand_dims(x, 0).T, 3, 1)

Same result.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.