[Numpy-discussion] Tuple outer product?

Robert Kern robert.kern at gmail.com
Fri Sep 25 15:33:21 EDT 2009


On Fri, Sep 25, 2009 at 14:19, Alan G Isaac <aisaac at 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.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list