We can join several 1d arrays with vstack
(or hstack
), e.g. D = np.vstack([a,b,c])
.
The reverse operation is [a2,b2,c2] = np.vsplit(D, 3)
.
But the dimensionality changes in the round-trip:
import numpy as np
a = np.random.rand(10,)
b = np.random.rand(10,)
c = np.random.rand(10,)
D = np.vstack([a,b,c])
[a2,b2,c2] = np.vsplit(D, 3)
>>> a.shape
(10,)
>>> a2.shape
(1, 10)
I know about squeeze to remove a dimension:
>>> a2.squeeze().shape
(10,)
But this is cumbersome, especially when splitting more than a couple of arrays.
Is there any way to 'automatically' perform a squeeze, or otherwise control the output of vsplit to avoid the mismatch in dimensions?
(the split docs do not mention any way to control the output dimensions as far as I can tell)
split
is using a slice to select rows, thus preserving that dimensionThat's a general behavior that lets it return other size splits.
But it appears you want to return one row at a time. There are many ways of doing this:
It's easy to apply
squeeze
iteratively (and not much more expensive, sincesplit
is already iterating):Or you can use a plain list comprehension:
Or convert the array to a list (this is different from
D.tolist()
:Or iteration by index. This is like
split
, but uses a scalar index rather than the slice. It's good to understand the difference betweenD[i,:]
andD[i:i+1, :]
.Since you are using unpacking, you don't need any of this. The unpacking will do the row 'iteration' for you:
you can try:
output: