python - 在第二个矩阵 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)] ]
解决方案
下面的答案非常具体到您的用例。我不确定您是否要解决更大的问题。但是从您的示例中给出 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.]])
推荐阅读
- java - 如何在单独的 docker Hazelcast 节点(嵌入在应用程序中的主节点)禁用数据的反序列化过程
- java - 为什么在使用 Gson.asString 时出现 java.lang.UnsupportedOperationException?
- python-3.x - 日志未显示在 AWS Cloudwatch 中
- sql - 如何修复 SQL Server 中的错误编码?
- powershell - 如何通过 SlackAPI 和 PSSlack 模块更改 Slack 的详细信息
- parsing - 将具有不同 col/rowspans 的电子表格转换为 HTML 表格
- css - 如何使用 css 为一系列类定义样式(.progress-10 到 .progress-40)
- swift - 理解 Swift 中的实例化 - OOP
- javascript - 从受保护的页面下载文件
- c# - Visual Studio 2019 SSDT 项目 SQLCLR 签名未生成签名的 DLL