[Numpy-discussion] Tuple outer product?

Mads Ipsen mpi at comxnet.dk
Fri Sep 25 16:01:07 EDT 2009


Robert Kern wrote:
> 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.
>
>   
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]]]


-- 
+------------------------------------------------------------+
| Mads Ipsen, Scientific developer                           |
+------------------------------+-----------------------------+
| QuantumWise A/S              | phone:         +45-29716388 |
| Nørresøgade 27A              | www:    www.quantumwise.com |
| DK-1370 Copenhagen, Denmark  | email:  mpi at quantumwise.com |
+------------------------------+-----------------------------+





More information about the NumPy-Discussion mailing list