[Numpy-discussion] Summing indices of heterogeneous shapes

Michael Hoffman b3i4old02 at sneakemail.com
Tue Apr 22 04:31:22 EDT 2008


Michael Hoffman wrote:
> In the following example I can sum up lists of column indices:
> 
>  >>> x = numpy.arange(30)
>  >>> x.shape = (6, 5)
>  >>> x
> array([[ 0,  1,  2,  3,  4],
>         [ 5,  6,  7,  8,  9],
>         [10, 11, 12, 13, 14],
>         [15, 16, 17, 18, 19],
>         [20, 21, 22, 23, 24],
>         [25, 26, 27, 28, 29]])
>  >>> cols = [[0, 1], [2, 3]]
>  >>> x[:, cols].sum(2)
> array([[ 1,  5],
>         [11, 15],
>         [21, 25],
>         [31, 35],
>         [41, 45],
>         [51, 55]])
> 
> Is there a way to do this if the shapes of the lists are heterogeneous? 
> For example, what if I wanted to set cols = [[0, 1], [2, 3], [1, 2, 3]]? 
> What's the best way to get a sensible result?

One way I thought of is to add an extra column to x that is full of 
zeros, and fill in any smaller lists in cols with that. But this will be 
pretty clunky and slow.




More information about the NumPy-Discussion mailing list