1

This should be easy...

I want to concatenate arrays A, B and C. It is possible that one or more of them may not exist or be empty. I want the remaining arrays to be concatenated. If, for example, B is empty, I want to concatenate A with C.

I've read these questions that seem relevant:

How can I check whether the numpy array is empty or not?

How do you 'remove' a numpy array from a list of numpy arrays?

I assume there's a 1-2 line way to do this.

Community
  • 1
  • 1
Tristan Klassen
  • 395
  • 1
  • 3
  • 9

1 Answers1

4

Concatenating empty arrays is not a problem:

In [1]: a = np.arange(10)

In [2]: b = np.array([])

In [3]: c = np.arange(3)

In [4]: np.concatenate((a,b,c))
Out[4]: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.,  0.,  1.,  2.])

For 2D arrays:

In [1]: a = np.arange(12.0).reshape((4,3))

In [2]: b = np.arange(24.0).reshape((8,3))

In [3]: c = np.array([])

In [4]: np.concatenate([x for x in [a,b,c] if x.size > 0])
Out[4]: 
array([[  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,   8.],
       [  9.,  10.,  11.],
       [  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,   8.],
       [  9.,  10.,  11.],
       [ 12.,  13.,  14.],
       [ 15.,  16.,  17.],
       [ 18.,  19.,  20.],
       [ 21.,  22.,  23.]])
user545424
  • 15,713
  • 11
  • 56
  • 70
  • I know that, but these aren't 1D arrays, except if they're empty. – Tristan Klassen Aug 02 '12 at 16:57
  • @TristanKlassen: What shape are the arrays? If they aren't 1D then you should also specify exactly what you mean when you say "concatenate". – user545424 Aug 02 '12 at 17:00
  • 2D. Concatenate along the axis where they're guaranteed to be the same size except if they're empty. – Tristan Klassen Aug 02 '12 at 17:03
  • @user545424 - did you skip the part in the explanation about the arrays being numpy? – Stefan H Aug 02 '12 at 17:03
  • @StefanH, well the question is tagged [numpy]. – user545424 Aug 02 '12 at 17:05
  • I get a " ValueError: concatenation of zero-length sequences is impossible ". I believe one of the input arrays doesn't exist, but this sounds like it's due to all of A, B and C being empty. I had to add exception handling for this. – Tristan Klassen Aug 02 '12 at 17:15
  • @TristanKlassen, please edit your original question and give a concrete example of arrays `a`, `b`, and `c` that you would like to be able to handle, and what you expect to get out. – user545424 Aug 02 '12 at 17:18