python - 按元素组合 2 个 2D numpy 数组,形状相同,同时保留它们的形状
问题描述
组合第一个数组和第二个数组中的每个元素并创建一个新数组,同时保持相同的形状。
#Numpy Array 1 -- shape 7 X 5
#X coordinates
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
#Numpy Array 2 -- shape 7 X 5
#Y coordinates
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5],
[6, 6, 6, 6, 6]])
所需的输出应该是一个元组数组。
#Desired Output -- shape 7 X 5
#(X,Y) combination
array([[(0,0), (1,0), (2,0), (3,0), (4,0)],
[(0,1), (1,1), (2,1), (3,1), (4,1)],
[(0,2), (1,2), (2,2), (3,2), (4,2)],
[(0,3), (1,3), (2,3), (3,3), (4,3)],
[(0,4), (1,4), (2,4), (3,4), (4,4)],
[(0,5), (1,5), (2,5), (3,5), (4,5)],
[(0,6), (1,6), (2,6), (3,6), (4,6)]])
解决方案
您可以执行以下操作:
import numpy as np
arr1 = np.array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
#Numpy Array 2 -- shape 7 X 5
#Y coordinates
arr2 = np.array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5],
[6, 6, 6, 6, 6]])
comb = np.vstack(([arr1.T], [arr2.T])).T
print(comb)
虽然它不是元组数组,但给出几乎相同的结果。
您可以在之后添加步骤以通过以下方式获取元组数组:
import numpy as np
arr1 = np.array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
#Numpy Array 2 -- shape 7 X 5
#Y coordinates
arr2 = np.array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5],
[6, 6, 6, 6, 6]])
comb = np.vstack(([arr1.T], [arr2.T])).T
f = np.vectorize(lambda x:tuple(*x.items()), otypes=[np.ndarray])
res = np.apply_along_axis(lambda x:dict([tuple(x)]), 2, comb)
mat2 = np.vstack(f(res))
这将给出以下内容:
[[(0, 0) (1, 0) (2, 0) (3, 0) (4, 0)]
[(0, 1) (1, 1) (2, 1) (3, 1) (4, 1)]
[(0, 2) (1, 2) (2, 2) (3, 2) (4, 2)]
[(0, 3) (1, 3) (2, 3) (3, 3) (4, 3)]
[(0, 4) (1, 4) (2, 4) (3, 4) (4, 4)]
[(0, 5) (1, 5) (2, 5) (3, 5) (4, 5)]
[(0, 6) (1, 6) (2, 6) (3, 6) (4, 6)]]
推荐阅读
- vue.js - vue组件数据在方法中没有改变
- c# - Specflow 2.3.2:为什么 Specflow 使用“Microsoft.VisualStudio.TestTools”而不是“NUnit.Framework”生成 *.cs 文件
- regex - 如何删除 URL 中的语言子文件夹并将这些页面重定向到非语言版本
- python-3.x - 一个测试示例可以属于多个类吗?
- java - 从 Java 密钥库导出和上传密钥 没有别名的密钥
- r - R中的ave()函数和mean()函数有什么区别?
- docker - '--disable-dev-shm-usage' 不能解决 Docker 中的 Chrome 崩溃问题
- python - 如何在 Python 调用的 matlab 函数中将 dict 作为参数传递
- python - 一次绘制多个直方图时如何创建 y 和 x 标签?
- python - 从满足 Pandas 特定条件的多索引数据帧构建时间序列