NumPy ndarray.repeat()
The numpy.ndarray.repeat()
method repeats elements of an array along a specified axis. This function is useful for expanding data in an array by duplicating its elements.
Syntax
ndarray.repeat(repeats, axis=None)
Parameters
Parameter | Type | Description |
---|---|---|
repeats | int or array_like | Number of times to repeat each element. Can be an integer (same repeat count for all elements) or an array specifying the repeat count per element. |
axis | int, optional | Axis along which to repeat values. If None , the input array is flattened before repeating. |
Return Value
Returns a new array with repeated values. The shape of the output array depends on the specified axis
and repeats
parameter.
Examples
1. Repeating Elements in a Flattened Array
In this example, we repeat each element of a 1D array a fixed number of times.
import numpy as np
# Creating a 1D array
arr = np.array([1, 2, 3])
# Repeating each element 3 times
result = arr.repeat(3)
print(result) # Output: [1 1 1 2 2 2 3 3 3]
Output:
[1 1 1 2 2 2 3 3 3]
The function repeats each element in sequence, producing a flattened output.
2. Repeating Elements Along a Specific Axis
Repeating elements in a 2D array along a specified axis.
import numpy as np
# Creating a 2D array
arr = np.array([[1, 2], [3, 4]])
# Repeating elements along axis 0 (rows)
result_axis0 = arr.repeat(2, axis=0)
print(result_axis0)
# Repeating elements along axis 1 (columns)
result_axis1 = arr.repeat(2, axis=1)
print(result_axis1)
Output:
[[1 2]
[1 2]
[3 4]
[3 4]]
[[1 1 2 2]
[3 3 4 4]]
Repeating along axis=0
duplicates rows, while axis=1
duplicates columns.
3. Specifying Different Repeats for Each Element
Using an array to define a different repeat count for each element.
import numpy as np
# Creating a 1D array
arr = np.array([10, 20, 30])
# Different repeat counts for each element
repeats = [1, 2, 3]
result = arr.repeat(repeats)
print(result)
Output:
[10 20 20 30 30 30]
Each element is repeated according to the corresponding value in the repeats
array.
4. Repeating Elements with a Different Count Along an Axis
Applying different repeat counts to elements along a specified axis.
import numpy as np
# Creating a 2D array
arr = np.array([[1, 2], [3, 4]])
# Repeating elements in different counts along axis 1
repeats = [1, 2] # Repeat first column once, second column twice
result = arr.repeat(repeats, axis=1)
print(result)
Output:
[[1 2 2]
[3 4 4]]
Elements in the first column are repeated once, while those in the second column are repeated twice.