Home > Software engineering >  Python Numpy Reshape an array to (m,n) shape that has less than m*n elements
Python Numpy Reshape an array to (m,n) shape that has less than m*n elements

Time:10-21

I am trying to convert a simple array into (m,n) shape but it has less than m*n elements.

My code:

list = [1,2,3,4,5]
ary = np.array(list)
reary = ary.reshpae(2,3)

Present answer:

ValueError: cannot reshape array of size 5 into shape (2,3)

Expected answer:

reary = 

[[1,2,3],
 [4,5]]

CodePudding user response:

Try this:

ary = np.array([1,2,3,4,5])

r, c = 2, 3
a = np.pad(ary, (0, r * c - len(ary))).reshape(r, c)
>>> a
array([[1, 2, 3],
       [4, 5, 0]])
  • Related