Mainland
Mainland

Reputation: 4584

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

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

Upvotes: 0

Views: 84

Answers (1)

Pierre D
Pierre D

Reputation: 26251

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

Upvotes: 1

Related Questions