1

I have an array with unknown length (for example lets use 11). so the array is

[1,2,3,4,5,6,7,8,9,10,11]

I want to reshape that array so he will have 5 columns and as much rows as needed. I know I can use reshape(-1,5) that way it creates the rows based on the array length.

But it gives me this error:

ValueError: cannot reshape array of size 11 into shape (5)

Any idea how do I do that? the desired result is:

[[1,2,3,4,5],
[6,7,8,9,10],
[11,None,None,None,None]]

The code that I ran and got this error is:

import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,10,11])    
print(np.reshape(a, (-1,5)))
1

2 Answers 2

1

You can do it without numpy.

ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
n = 5
reshaped = [ar[i: i + n] + [None] * (i + n - len(ar)) for i in range(0, len(ar), n)]

You can also use trick with iterator (chunks will be in tuples):

reshaped = list(zip(*[iter(ar + [None] * (n - len(ar) % n))] * n))

You can apply zip_longest() from itertools to not add None values by yourself:

from itertools import zip_longest
reshaped = list(zip_longest(*[iter(ar)] * n))
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a more efficient way? maybe one numpy function or withput loops?
@orr. what do you mean under "efficient"? You can't split list to chunks without loops. I'm not specialist in numpy, so I don't know it's methods.
by efficient I mean built-in numpy functions so that will make faster runtime. your answer is great, but I am curious to knoe whether there is faster way.
@orr, if tests from this answer is correct, numpy 3 times slower then list comprehension.
haha thats funny, I thought numpy should be more faster. I guess I was wrong, thanks for the enlightenment.
0
In [135]: res = np.empty((3,5), object)                                                                      
In [136]: res                                                                                                
Out[136]: 
array([[None, None, None, None, None],
       [None, None, None, None, None],
       [None, None, None, None, None]], dtype=object)
In [137]: res.flat[:11] = np.arange(1,12)                                                                    
In [138]: res                                                                                                
Out[138]: 
array([[1, 2, 3, 4, 5],
       [6, 7, 8, 9, 10],
       [11, None, None, None, None]], dtype=object)

2 Comments

the thing is I dont know the row number, so I dont know the size of the empty None array I need. I only know the columns
But you can calculate the row number. The next multiple of 5 up from 11 is 15. 15/5 gives me 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.