Introduction to NumPy and Matplotlib
Chapter 5: Array manipulation
Repeating arrays
You can also repeat an array easily with np.repeat()
.
>>> print(np.repeat(0, 2))
[0 0]
>>> x = np.array([[1, 2],[3, 4]])
>>> print(x)
[[1 2]
[3 4]]
>>> print(np.repeat(x, 2)) # Use flattened array if you do not specify the axis
[1 1 2 2 3 3 4 4]
>>> print(np.repeat(x, 2, axis=0))
[[1 2]
[1 2]
[3 4]
[3 4]]
>>> print(np.repeat(x, 2, axis=1))
[[1 1 2 2]
[3 3 4 4]]
You can also specify a different number of repeats for each row individually. See the documentation to find out how!
Another similar function is np.tile()
. Spot the difference between np.repeat()
and np.tile()
!
>>> x = np.array([[1, 2],[3, 4]])
>>> print(x)
[[1 2]
[3 4]]
>>> print(np.tile(x, 2))
[[1 2 1 2]
[3 4 3 4]]
>>> print(np.tile(x, (3, 2)))
[[1 2 1 2]
[3 4 3 4]
[1 2 1 2]
[3 4 3 4]
[1 2 1 2]
[3 4 3 4]]