Say I have a 1-dimensional numpy array with shape (5,):
a = np.array(range(0,5))
And I want to transform it two a 2-dimensional array by duplicating the array above 3 times, so that the shape will be (5,3), for example:
array([[0,1,2,3,4],
[0,1,2,3,4],
[0,1,2,3,4]])
How would I do that? I know that with lists, you can use list.copy() to create a copy, but I don't want to convert my array to a list first.
Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.
int rows = 4; int cols = 6; int array1D[rows*cols] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24} int array2D[rows][cols]; int offset = 2; //Offset is always going to be 2 for(int i = 0; i < cols; i++) for(int j = 0; j < rows; i++) array2D[j][i] = array1D[i + j*offset];
reshape which is used to convert a 1-D array into a 2-D array of required dimensions (n x m). This function gives a new required shape without changing the data of the 1-D array. Parameters: array: is the given 1-D array that will be given a new shape or converted into 2-D array.
With numpy.tile
.
>>> a = np.arange(5)
>>> np.tile(a, (3, 1))
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
You can use *
operator on list.
import numpy as np
arr = np.array(3*[range(0,5)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With