繁体   English   中英

向量元组列表 - >两个矩阵

[英]List of tuples of vectors --> two matrices

在Python中,我有一个元组列表,每个元组都包含两个nx1向量。

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]))]

现在,我想将此列表拆分为两个矩阵,向量为列。
所以我想要:

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

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


现在,我有以下内容:

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

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

    return (x,y)

这工作正常,但我想知道是否存在更清晰的方法,它不使用zip(*)函数和/或不需要转换和转置x和y矩阵。

这是纯粹的娱乐,因为如果我要做你想做的事情,我会使用zip解决方案。

但是没有zipping的方法vstack沿着轴1的vstack

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]])

比较所有先前提出的方法的最佳元素,我认为最好如下*:

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)

*这是我的代码片段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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