Question
I have an array: foo = [1,2,3,4,5,6,7,8,9,10]
And I was wondering the best way to get this array on the following shape:
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[10.]]
How should I do ?
Thanks!
What I currently do
Since foo
doesn't contains multiple of 3 elements using numpy.reshape()
gives an error
import numpy as np
np.reshape(foo,(-1,3))
ValueError: cannot reshape array of size 10 into shape (3)
So I need to force my array to contain multiple of 3 elements, either by dropping some (but I lose some data):
_foo = np.reshape(foo[:len(foo)-len(foo)%3],(-1,3))
print(_foo)
[[1 2 3]
[4 5 6]
[7 8 9]]
Or by extending with nan
:
if len(foo)%3 != 0:
foo.extend([np.nan]*((len(foo)%3)+1))
_foo = np.reshape(foo,(-1,3))
print(_foo)
[[ 1. 2. 3.]
[ 4. 5. 6.]
[ 7. 8. 9.]
[10. nan nan]]
Notes
- @cᴏʟᴅsᴘᴇᴇᴅ recommendation is rather to work with full arrays instead (padding with
nan
or0
for instance)