簡體   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