[Numpy-discussion] Tuple outer product?

Gökhan Sever gokhansever@gmail....
Fri Sep 25 15:37:59 CDT 2009


On Fri, Sep 25, 2009 at 3:01 PM, Mads Ipsen <mpi@comxnet.dk> wrote:

> Robert Kern wrote:
> > On Fri, Sep 25, 2009 at 14:19, Alan G Isaac <aisaac@american.edu> wrote:
> >
> >> I do not see what is wrong with itertools.product,
> >> but if you hate it, you can use numpy.meshgrid:
> >>
> >>
> >>>>> np.array(np.meshgrid([1,2,3],[4,5,6])).transpose()
> >>>>>
> >> array([[[1, 4],
> >>         [1, 5],
> >>         [1, 6]],
> >>
> >>        [[2, 4],
> >>         [2, 5],
> >>         [2, 6]],
> >>
> >>        [[3, 4],
> >>         [3, 5],
> >>         [3, 6]]])
> >>
> >
> > If you need more than two item sets, or are using Python 2.5:
> >
> > import numpy as np
> >
> > def cartesian_product(*items):
> >     items = map(np.asarray, items)
> >     lengths = map(len, items)
> >     n = np.arange(np.product(lengths))
> >     results = []
> >     for i in range(-1, -len(items)-1, -1):
> >         j = n % lengths[i]
> >         results.insert(0, items[i][j])
> >         n -= j
> >         n //= lengths[i]
> >     results = np.column_stack(results)
> >     results.shape = tuple(lengths + [len(items)])
> >     return results
> >
> >
> > The final shape manipulations are, of course, optional.
> >
> >
> Thanks for all the suggestions. Came up with this, which I think I'll
> stick with
>
> a = numpy.array([1,2,3])
> b = numpy.array([4,5,6])
>
> (n,m) = (a.shape[0],b.shape[0])
> a = numpy.repeat(a,m).reshape(n,m)
> b = numpy.repeat(b,n).reshape(m,n).transpose()
> ab = numpy.dstack((a,b))
>
> print ab.tolist()
>
> [[[1, 4], [1, 5], [1, 6]], [[2, 4], [2, 5], [2, 6]], [[3, 4], [3, 5],
> [3, 6]]]
>
>
>
Yes this is super fast indeed :)

with 10000x10000

I[12]: %time run test.py
CPU times: user 6.14 s, sys: 1.83 s, total: 7.97 s
Wall time: 8.25 s

#test.py

import numpy

a = numpy.arange(10000)
b = numpy.arange(10000)

(n,m) = (a.shape[0],b.shape[0])
a = numpy.repeat(a,m).reshape(n,m)
b = numpy.repeat(b,n).reshape(m,n).transpose()
ab = numpy.dstack((a,b))


> --
> +------------------------------------------------------------+
> | Mads Ipsen, Scientific developer                           |
> +------------------------------+-----------------------------+
> | QuantumWise A/S              | phone:         +45-29716388 |
> | Nørresøgade 27A              | www:    www.quantumwise.com |
> | DK-1370 Copenhagen, Denmark  | email:  mpi@quantumwise.com |
> +------------------------------+-----------------------------+
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>



-- 
Gökhan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20090925/84c9f3b4/attachment-0001.html 


More information about the NumPy-Discussion mailing list