Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform 1D Array to 2D Array with duplication [duplicate]

Tags:

python

numpy

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.

like image 282
Tim Avatar asked Nov 26 '18 12:11

Tim


People also ask

How do you convert a 1D array to a 2D array?

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.

How do you convert a 1D array to a 2D array in CPP?

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];

How will you change the following 1D list into a 2D NumPy array as shown below?

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.


2 Answers

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]])
like image 178
timgeb Avatar answered Oct 19 '22 20:10

timgeb


You can use * operator on list.

import numpy as np
arr = np.array(3*[range(0,5)])
like image 37
Oli Avatar answered Oct 19 '22 20:10

Oli