pythonnumpynumpy-ndarraymemory-efficient

Given two arrays A and B, how to efficiently combine them so that the output is an array in which each element is a tuple (Aij,Bij)?)


Consider two arrays A and B, both of dimension NxN. I wish to generate a new array NxN such that each new element is a tuple (or list, doesn't really matter) of the type (A_ij,B_ij).

I can do it by running element by element like:

def recombine(A,B):
    NewArray=[]
    for i in range(len(A)):
        NewArray.append([])
        for j in range(len(B)):
            NewArray[i].append(A[i][j],B[i][j])
    return NewArray

which is a very memory consuming algorithm.

I was wondering if there is a more efficient way (taking advantage of numpy array for doing this).

To clarify, let's consider the following example (where, for simplicity, I am considering simple lists instead of np arrays):

A=[[1,2],[3,4]]
B=[[10,20],[30,40]]

#I want an output in the form:

[[(1,10),(2,20)],[(3,30),(4,40)]]

Solution

  • You can use nested zip. zip yields tuples from a set of iterables where each item in the tuple is the next value of each iterable in turn. First you zip A and B which yields sublists in A and B, then a second zip to flip them.

    >>> A=[[1,2],[3,4]]
    >>> B=[[10,20],[30,40]]
    >>> [list(zip(*zipped)) for zipped in zip(A,B)]
    [[(1, 10), (2, 20)], [(3, 30), (4, 40)]]