4

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?

2
  • what values have a1, a2 when error occurs? Commented Dec 4, 2013 at 14:51
  • Please confirm that the dimensions are (0,) and (5,). Commented Dec 4, 2013 at 14:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

If I understand OP correctly, the array dimensions are (0,) and (5,) so it should be fine.
You are right. The dimensions are (5, 2) and (0,), but I do not control the dimensions of the empty array. How do I ensure the second dimension of a2 is 2?
If a2 is empty, you can do a2.reshape((0,2)) - it will create 2D empty array with second dimension 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.