I was trying to concatenate 1-D two arrays in Python, using numpy. One of the arrays might potentially be empty (a2 in this case). a1 and a2 are the results from some computation over which I have no control. When a1 and a2 are non-empty they both have shapes of the form (n,2), so concatenation is not a problem. However it could turn out that one of them is empty, in which case its size becomes (0,). Hence the concatenation throws up an error.
s1=array(a1).shape
s2=array(a2).shape
print(s1) #(5,2)
print(s2) #(0,)
s3=hstack((a1, a2))
s3=concatenate((a1, a2), 0)
Error: ValueError: all the input arrays must have same number of dimensions
I see other stackoverflow questions where it is said that it is possible to concatenate an empty array. How do I ensure that the empty array's size is (0,2)? Can someone help me out?
The error message tells you what you need to know. It's not enough that the array is empty - they have to have the same number of dimensions. You are looking only at the first element of shape - but shape can have more than one element:
numpy.array([[]]).shape # (1L, 0L)
numpy.array([[]]).transpose.shape # (0L, 1L)
numpy.array([]).shape # (0L, )
So you see, empty arrays can have different numbers of dimensions. This may be your problem.
EDIT solution to create an empty array of the right size is to reshape it:
a2.shape() # (0L,)
a2 = a2.reshape((0,2))
a2.shape() # (0L, 2L)
This should solve your problem.
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