简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM