Introduction
One common operation is duplicating (or repeating) a column of values along the y-axis to create a 2D array with multiple columns. This article demonstrates how to achieve this using np.repeat
.
Using np.repeat
np.repeat
allows you to duplicate elements along a specific axis in a NumPy array. When dealing with a column array, you can repeat its values horizontally (along the y-axis or axis=1
) to create a 2D array with repeated columns.
Example 1: Repeating Numeric Values
Here’s how to duplicate a column of integers multiple times:
1 2 3 4 5 6 7 8 9 10 11 | import numpy as np # Define a column array c = np.array([[1], [2], [3], [5], [7], [11]]) print(c) # Original array print(c.shape) # Shape of the original array # Repeat the column 4 times along the y-axis result = np.repeat(c, 4, axis=1) print(result) # Output after repeating |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | [[ 1] [ 2] [ 3] [ 5] [ 7] [11]] (6, 1) [[ 1 1 1 1] [ 2 2 2 2] [ 3 3 3 3] [ 5 5 5 5] [ 7 7 7 7] [11 11 11 11]] |
Example 2: Repeating Boolean Values
The same operation can be performed on a column of boolean values:
1 2 3 4 5 6 7 8 9 10 11 | import numpy as np # Define a column array of booleans c = np.array([[False], [True], [False], [False], [False], [True]]) print(c) # Original array print(c.shape) # Shape of the original array # Repeat the column 4 times along the y-axis result = np.repeat(c, 4, axis=1) print(result) # Output after repeating |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | [[False] [ True] [False] [False] [False] [ True]] (6, 1) [[False False False False] [ True True True True] [False False False False] [False False False False] [False False False False] [ True True True True]] |
Key Points to Remember
-
Input Format: The input array must have the shape
(n, 1)
for proper duplication along the y-axis. If the input is a 1D array, reshape it first usingarray.reshape(-1, 1)
. -
axis=1
: This specifies the horizontal direction (columns) for duplication. -
Flexible Applications:
np.repeat
works with various data types, including integers, floats, booleans, and more.
Use Cases
Note: This approach has been used to vectorize a research code and improve its performance. More details can be found How to Plot CloudSat 2B-CLDCLASS-LIDAR Product Using Python ?.
References
Links | Site |
---|---|
numpy.repeat | numpy.org |