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 Answers2

4

Try this code:

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

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

Shadab Hussain
  • 794
  • 6
  • 24
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.

Mohammad Jafar Mashhadi
  • 4,102
  • 3
  • 29
  • 49