Numpy array concatenation

Viewed 57

In some special cases, array can be concatenated without explicitly calling concatenate function. For example, given a 2D array A, the following code will yield an identical array B:

B = np.array([A[ii,:] for ii in range(A.shape[0])])

I know this method works, but do not quite understand the underlying mechanism. Can anyone demystify the code above a little bit?

2 Answers
  • A[ii,:] is ii-th row of array A.

  • The list comprehension [A[ii,:] for ii in range(A.shape[0])] basically makes a list of rows in A (A.shape[0] is number of rows in A).

  • Finally, B is an array, that its content is a list of A's rows, which is essentially the same as A itself.

By now you should be familiar with making an array from a list of lists:

In [178]: np.array([[1,2],[3,4]])                                                                    
Out[178]: 
array([[1, 2],
       [3, 4]])

but that works just as well if it's a list of arrays:

In [179]: np.array([np.array([1,2]),np.array([3,4])])                                                
Out[179]: 
array([[1, 2],
       [3, 4]])

stack also does this, by adding a dimension to the arrays and calling concatenate (read its code):

In [180]: np.stack([np.array([1,2]),np.array([3,4])])                                                
Out[180]: 
array([[1, 2],
       [3, 4]])

concatenate joins the arrays - on an existing axis:

In [181]: np.concatenate([np.array([1,2]),np.array([3,4])])                                          
Out[181]: array([1, 2, 3, 4])

stack adds a dimension first, as in:

In [182]: np.concatenate([np.array([[1,2]]),np.array([[3,4]])])                                      
Out[182]: 
array([[1, 2],
       [3, 4]])

np.array and concatenate aren't identical, but there's a lot of overlap in their functionality.

Related