简体   繁体   中英

List of tuples of vectors --> two matrices

In Python, I have a list of tuples, each of them containing two nx1 vectors.

data = [(np.array([0,0,3]), np.array([0,1])),
        (np.array([1,0,4]), np.array([1,1])),
        (np.array([2,0,5]), np.array([2,1]))]

Now, I want to split this list into two matrices, with the vectors as columns.
So I'd want:

x = np.array([[0,1,2],
              [0,0,0],
              [3,4,5]])

y = np.array([[0,1,2],
              [1,1,1]])


Right now, I have the following:

def split(data):
    x,y = zip(*data)

    np.asarray(x)
    np.asarray(y)
    x.transpose()
    y.transpose()

    return (x,y)

This works fine, but I was wondering whether a cleaner method exists, which doesn't use the zip(*) function and/or doesn't require to convert and transpose the x and y matrices.

This is for pure entertainment, since I'd go with the zip solution if I were to do what you're trying to do.

But a way without zipping would be vstack along your axis 1.

a = np.array(data) 
f = lambda axis: np.vstack(a[:, axis]).T 

x,y = f(0), f(1)

>>> x
array([[0, 1, 2],
       [0, 0, 0],
       [3, 4, 5]])

>>> y
array([[0, 1, 2],
       [1, 1, 1]])

Comparing the best elements of all previously proposed methods, I think it's best as follows*:

def split(data):
    x,y = zip(*data)         #splits the list into two tuples of 1xn arrays, x and y

    x = np.vstack(x[:]).T    #stacks the arrays in x vertically and transposes the matrix
    y = np.vstack(y[:]).T    #stacks the arrays in y vertically and transposes the matrix

    return (x,y)

* this is a snippet of my code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM