[Numpy-discussion] Interleaved Arrays and

Neil Martinsen-Burrell nmb at wartburg.edu
Tue Jun 16 16:14:35 EDT 2009


On 06/16/2009 02:18 PM, Robert wrote:
>   >>>  n = 10
>   >>>  xx = np.ones(n)
>   >>>  yy = np.arange(n)
>   >>>  aa = np.column_stack((xx,yy))
>   >>>  bb = np.column_stack((xx+1,yy))
>   >>>  aa
> array([[ 1.,  0.],
>          [ 1.,  1.],
>          [ 1.,  2.],
>          [ 1.,  3.],
>          [ 1.,  4.],
>          [ 1.,  5.],
>          [ 1.,  6.],
>          [ 1.,  7.],
>          [ 1.,  8.],
>          [ 1.,  9.]])
>   >>>  bb
> array([[ 2.,  0.],
>          [ 2.,  1.],
>          [ 2.,  2.],
>          [ 2.,  3.],
>          [ 2.,  4.],
>          [ 2.,  5.],
>          [ 2.,  6.],
>          [ 2.,  7.],
>          [ 2.,  8.],
>          [ 2.,  9.]])
>   >>>  np.column_stack((aa,bb))
> array([[ 1.,  0.,  2.,  0.],
>          [ 1.,  1.,  2.,  1.],
>          [ 1.,  2.,  2.,  2.],
>          [ 1.,  3.,  2.,  3.],
>          [ 1.,  4.,  2.,  4.],
>          [ 1.,  5.,  2.,  5.],
>          [ 1.,  6.,  2.,  6.],
>          [ 1.,  7.,  2.,  7.],
>          [ 1.,  8.,  2.,  8.],
>          [ 1.,  9.,  2.,  9.]])
>   >>>  cc = _
>   >>>  cc.reshape((n*2,2))
> array([[ 1.,  0.],
>          [ 2.,  0.],
>          [ 1.,  1.],
>          [ 2.,  1.],
>          [ 1.,  2.],
>          [ 2.,  2.],
>          [ 1.,  3.],
>          [ 2.,  3.],
>          [ 1.,  4.],
>          [ 2.,  4.],
>          [ 1.,  5.],
>          [ 2.,  5.],
>          [ 1.,  6.],
>          [ 2.,  6.],
>          [ 1.,  7.],
>          [ 2.,  7.],
>          [ 1.,  8.],
>          [ 2.,  8.],
>          [ 1.,  9.],
>          [ 2.,  9.]])
>   >>>
>
>
> However I feel too, there is a intuitive abbrev function like
> 'interleave' or so missing in numpy shape_base or so.

Using fancy indexing, you can set strided portions of an array equal to 
another array.  So::

In [2]: aa = np.empty((10,2))

In [3]: aa[:, 0] = 1

In [4]: aa[:,1] = np.arange(10)

In [5]: bb = np.empty((10,2))

In [6]: bb[:,0] = 2

In [7]: bb[:,1] = aa[:,1] # this works

In [8]: cc = np.empty((20,2))

In [9]: cc[::2,:] = aa

In [10]: cc[1::2,:] = bb

In [11]: cc
Out[11]:
array([[ 1.,  0.],
        [ 2.,  0.],
        [ 1.,  1.],
        [ 2.,  1.],
        [ 1.,  2.],
        [ 2.,  2.],
        [ 1.,  3.],
        [ 2.,  3.],
        [ 1.,  4.],
        [ 2.,  4.],
        [ 1.,  5.],
        [ 2.,  5.],
        [ 1.,  6.],
        [ 2.,  6.],
        [ 1.,  7.],
        [ 2.,  7.],
        [ 1.,  8.],
        [ 2.,  8.],
        [ 1.,  9.],
        [ 2.,  9.]])

Using this syntax, interleave could be a one-liner.

-Neil



More information about the NumPy-Discussion mailing list