The Python Oracle

Convert a 1D array to a 2D array in numpy

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

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//ncols by -1 to compute the proper shape automatically. Make sure that a.shape[0]*a.shape[1]=a.size, else you'll run into some problem.

  • You can get a new array with the np.reshape function, that works mostly like the version presented above

    new = np.reshape(a, (-1, ncols))
    

    When it's possible, new will be just a view of the initial array a, meaning that the data are shared. In some cases, though, new array will be acopy instead. Note that np.reshape also accepts an optional keyword order that lets you switch from row-major C order to column-major Fortran order. np.reshape is the function version of the a.reshape method.

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))