가끔씩 사용할 때가 있긴 하다 그러나 많이 있지는 않다. 그러나 이런 API를 모를 때 for문을 사용할 수 밖에 없게 된다.
numpy.repeat(a, repeats, axis = None)
어떤 array를 몇번 반복시킬지 축에 대해서 반복시킬지 결정할 수 있다.
scalar에 대하여 repeat 하는 경우
import numpy as np
x = 3
rep = np.repeat(x,2) [3 3]
vector에 대하여 repeat 하는 경우
import numpy as np
x = np.array([1,2,3])
rep = np.repeat(x,3) [1 1 1 2 2 2 3 3 3]
위의 예제를 통해 알 수 있는 것은 repeat는 원소별로 반복시키는 API이다.
행렬 ndarrray repeat
import numpy as np
x = np.arange(4).reshape((2,2)) [[0 1]
[2 3]]
rep = np.repeat(x,3) [0 0 0 1 1 1 2 2 2 3 3 3]
axis가 명시되지 않았기 때문에 vector 취급을 해버린다.
axis가 명시되어 있는 경우
import numpy as np
x = np.arange(4).reshape((2,2)) [[0 1]
[2 3]]
rep = np.repeat(x, repeats = 3, axis = 0) [[0 1]
[0 1]
[0 1]
[2 3]
[2 3]
[2 3]]
rep = np.repeat(x, repeats = 3, axis = 1) [[0 0 0 1 1 1]
[2 2 2 3 3 3]]
repeat 활용 방안
import numpy as np
x = np.arange(4).reshape((2,2)) [[0 1]
[2 3]]
rep = np.repeat(x, repeats = [2, 1], axis = 0) [[0 1]
[0 1]
[2 3]]
import numpy as np
x = np.arange(4).reshape((2,3)) [[0 1 2]
[3 4 5]]
rep = np.repeat(x, repeats=[2 1 2], axis = 1)
[[0 0 1 2 2]
[3 3 4 5 5]]
numpy.tile(A, reps)
repeat는 원소별로 반복을 시켰었다면 tile은 전체 A를 반복시키는 컨셉이다.
import numpy as np
a = np.arange(4) [0 1 2 3]
tile = np.tile(a, reps = 3) [0 1 2 3 0 1 2 3 0 1 2 3]
vector에 tile을 사용할 경우
import numpy as np
a = np.arange(3) [0 1 2]
tile = np.tile(a, reps = [1,2]) [[0 1 2 0 1 2]]
tile = np.tile(a, reps = [2,1]) [[0 1 2]
[0 1 2]]
tile = np.tile(a, reps = [2,2]) [[0 1 2 0 1 2]
[0 1 2 0 1 2]]
axis별로 몇 번씩 반복할 것인지 결정해준다.