Is there any built-in numpy function that would get:
a=np.asarray([[[1,2],[3,4]],[[1,2],[3,4]]])
And would return:
b=[[1,2],[3,4],[1,2],[3,4]]
? Something like like one layer flattening.
P.S. I am looking for a vectorized option otherwise this dumb code is available:
flat1D(a):
b=np.array([])
for item in a:
b=np.append(b,item)
return b
You can simply reshape the array.
>>> a.reshape(-1,a.shape[-1])
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
The shown code returns a 1D array, to do this:
>>> a.ravel()
array([1, 2, 3, 4, 1, 2, 3, 4])
Or, if you are sure you want to copy the array:
>>> a.flatten()
array([1, 2, 3, 4, 1, 2, 3, 4])
The difference between ravel and flatten primarily comes from the fact that flatten will always return a copy and ravel will return a view if possible and a copy if not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With