1

I have a coordinate saved as a numpy array x = np.array([1,2]) and I am trying to create an array that repeats [1,2] n times. For example, to repeat 4 times, I would want the array to look like this:

array([1,2],[1,2],[1,2],[1,2])

I have tried using the function:

np.repeat(x, 4, axis=0)

but the output is flattened array that looks like this:

array([1,1,1,1,2,2,2,2])

Does anyone know how to do this?

cp0515
  • 25
  • 1
  • 4

5 Answers5

5

Simplest way should be [[1,2]]*4

[[1,2]]*4

[[1, 2], [1, 2], [1, 2], [1, 2]]

If you wanna make it array, np.array([[1,2]]*4) would work.

smttsp
  • 4,011
  • 3
  • 33
  • 62
0

I defined a function for this problem. You can use below function called repeatList:

import numpy as np
myListToRepeat = [1,2]
def repeatList(initList , n):
    returnList = []
    for i in range(n):
        returnList.append(initList)
    return returnList
npArray = np.array(repeatList(myListToRepeat , 4))
print(npArray)

Output

[[1 2]
 [1 2]
 [1 2]
 [1 2]]
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
0

you need to give as below You have to create an array which has 2 dimension Then your inner array will an element for axis=0. repeating will be done to

import numpy as np
num = np.array(([[1,2]]))
print(np.repeat(num,4,axis =0))#[[1 2] [1 2] [1 2] [1 2]]
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45
0
import numpy as np
x = np.array([1, 2])
np.tile(x,[2,1])
>>> array([[1, 2],
       [1, 2]])

>>> np.tile(x,[4,1])
array([[1, 2],
       [1, 2],
       [1, 2],
       [1, 2]])
luthervespers
  • 258
  • 1
  • 2
  • 10
-1

Instead of numpy repeat use numpy tile. This fits your case: https://numpy.org/doc/stable/reference/generated/numpy.tile.html

>>> import numpy as np
>>> t = np.array([1, 2])
>>> np.tile(t, 4)
array([1, 2, 1, 2, 1, 2, 1, 2])
Edwin Cheong
  • 879
  • 2
  • 7
  • 12