Question
I have an array: foo = [1,2,3,4,5,6,7,8,9,10]
And I was wondering how best to get this array in the following form:
[[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[10.]]
How do i do
Thank!
What am i doing now
Since it foodoes not contain several of the three elements, using numpy.reshape(), throws an error
import numpy as np
np.reshape(foo,(-1,3))
ValueError: unable to resize array 10 to form (3)
Therefore, I need to force my array to contain several of the three elements, either discarding some (but I will 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 expanding 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ᴘᴇᴇᴅ is recommended to work with full arrays more quickly (for example, using
nanor 0)