0
votes

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]]
1
you can't do jagged arrays, but you can use padding.Pierre D
Numpy expects the items in your array to match the new shape you want to reshape to, therefore your approach does not work.sehan2
@PierreD what is padding?Mainland
Padding means to add for example a fixed numer of zeros to make up for the missing values. So in your case append a zero and then reshape. numpy.org/doc/stable/reference/generated/numpy.pad.htmlsehan2
As you can tell, your expected reary does not have a shape of (2,3)ssm

1 Answers

0
votes

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