May 1, 2013

Numpy - Dstack, Vstack and Hstack

Dstack
Stack arrays in sequence depth-wise.
i.e. returns
[ [ a[i], b[i] ], 
  [ a[j], b[j] ], 
  [ a[k], b[k] ],
...]

In [1]: a=np.array([1,2,3])

In [2]: b=np.array([4,5,6])

In [3]: np.dstack((a,b))
Out[3]: 
array([[[1, 4],
        [2, 5],
        [3, 6]]])
Vstack
Stack arrays vertically
In [7]: np.vstack((a,b))
Out[7]: 
array([[1, 2, 3],
       [4, 5, 6]])
Hstack
Stack arrays horizontally
In [8]: np.hstack((a,b))
Out[8]: array([1, 2, 3, 4, 5, 6])
Equivalent np.concatenate operations
np.vstack(tup) => np.concatenate(tup, axis=0)
np.hstack(tup) => np.concatenate(tup, axis=1)
np.dstack(tup) => np.concatenate(tup, axis=2)
Note: Axis => refers to the axis along which the concatenation happens. As a consequence, this also happens to be the dimension where the numbers may be different.
Eg: For vstack, concatenation happens on axis 0
i.e. a (5x3) and (2x3) array can be passed in to vstack to generate a (7x3) array.