首页 > 解决方案 > 在第二个矩阵 numpy 的同时逐列读取矩阵

问题描述

我有2个矩阵。第一个矩阵被每一列遍历,每一列被分配一个第二个矩阵,如示例中所示 下面只是一个示例。我需要不同维度的矩阵

import numpy as np
arr1=np.array([[11, 21,31], [12, 22,32], [13, 23,32], [14, 24,34]])
arr2=np.array([1,2,3,4])

我需要

 # 1st column from arr1
    11 1
    12 2
    13 3
    14 4
#2nd column from arr1
    21 1
    22 2
    23 3
    24 4
#3th column from arr1   
    31 1
    32 2
    33 3
    34 4

我尝试了不同的选择。例如,即使预先准备好我的结果也是这样

print(*(f' {i} 0\n'.join(s.split() + ['']) for s, i in zip(arr1.splitlines(),arr2.split())), sep="") 

我的结果

11 1 
21 1 
31 1 
12 2 
22 2 
32 2 
13 3 
23 3 
33 3 
14 4 
24 4 
34 4 

我也试过这个,但它没有用

osem = np.vstack([ np.c_[arr1[:,x], arr2[:,y]]
        for x, y in np.c_[np.triu_indices(n=arr.shape[1], k=1)] ]

标签: pythonpython-3.xnumpy

解决方案


下面的答案非常具体到您的用例。我不确定您是否要解决更大的问题。但是从您的示例中给出 arr1 和 arr2 ,您可以使用以下代码

a = np.zeros((arr1.flatten().shape[0],2)) #init the new array
a[:,[0]] = arr1.T.flatten()[:,None]  #fill the first column with the values
a[:,[1]] = np.tile(arr2,3)[:,None]  # fill the second column with values
a
>>>
Out[39]: 
array([[11.,  1.],
       [12.,  2.],
       [13.,  3.],
       [14.,  4.],
       [21.,  1.],
       [22.,  2.],
       [23.,  3.],
       [24.,  4.],
       [31.,  1.],
       [32.,  2.],
       [32.,  3.],
       [34.,  4.]])

推荐阅读