Convert a 1D array to a 2D array in numpy
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping
--
Chapters
00:00 Convert A 1d Array To A 2d Array In Numpy
00:30 Accepted Answer Score 289
00:44 Answer 2 Score 15
01:02 Answer 3 Score 55
02:18 Answer 4 Score 14
02:25 Thank you
--
Full question
https://stackoverflow.com/questions/1257...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #matrix #numpy #multidimensionalarray
#avk47
ACCEPTED ANSWER
Score 289
You want to reshape the array.
B = np.reshape(A, (-1, 2))
where -1 infers the size of the new dimension from the size of the input array.
ANSWER 2
Score 55
You have two options:
If you no longer want the original shape, the easiest is just to assign a new shape to the array
a.shape = (a.size//ncols, ncols)You can switch the
a.size//ncolsby-1to compute the proper shape automatically. Make sure thata.shape[0]*a.shape[1]=a.size, else you'll run into some problem.You can get a new array with the
np.reshapefunction, that works mostly like the version presented abovenew = np.reshape(a, (-1, ncols))When it's possible,
newwill be just a view of the initial arraya, meaning that the data are shared. In some cases, though,newarray will be acopy instead. Note thatnp.reshapealso accepts an optional keywordorderthat lets you switch from row-major C order to column-major Fortran order.np.reshapeis the function version of thea.reshapemethod.
If you can't respect the requirement a.shape[0]*a.shape[1]=a.size, you're stuck with having to create a new array. You can use the np.resize function and mixing it with np.reshape, such as
>>> a =np.arange(9)
>>> np.resize(a, 10).reshape(5,2)
ANSWER 3
Score 15
Try something like:
B = np.reshape(A,(-1,ncols))
You'll need to make sure that you can divide the number of elements in your array by ncols though. You can also play with the order in which the numbers are pulled into B using the order keyword.
ANSWER 4
Score 14
If your sole purpose is to convert a 1d array X to a 2d array just do:
X = np.reshape(X,(1, X.size))