Convert a 1D array to a 2D array in numpy
--
Track title: CC P Beethoven - Piano Sonata No 2 in A
--
Chapters
00:00 Question
00:43 Accepted answer (Score 267)
01:01 Answer 2 (Score 54)
02:40 Answer 3 (Score 14)
02:54 Answer 4 (Score 14)
03:19 Thank you
--
Full question
https://stackoverflow.com/questions/1257...
Accepted answer links:
[reshape]: http://docs.scipy.org/doc/numpy/referenc...
--
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))