简体   繁体   English

Python:在numpy数组上按元素明智的操作构建矩阵

[英]Python: Building Matrix by element wise operations on numpy arrays

Given two numpy arrays (arr1 and arr2) I want to build a matrix that stores the difference of each element in arr1 with each element in arr2. 给定两个numpy数组(arr1和arr2),我想构建一个矩阵,用于存储arr1中每个元素与arr2中每个元素的差。 ie: 即:

my_matrix = [arr1-i for i in arr2]

However this starts to get slow as the arrays get larger in size. 但是,随着阵列变大,这种情况开始变慢。 I've tried to make use of numpy's good performance like so: 我试图像这样利用numpy的良好性能:

arr1_mtx = np.array([arr1]*len(arr2))
arr2_mtx = np.array([arr1]*len(arr2)).T
my_matrix = arr1_mtx-arr2_mtx

I'm quite new to Python so I'm not sure if this is the most pythonic and efficient way to build this matrix. 我对Python还是很陌生,所以我不确定这是否是构建该矩阵的最pythonic和最有效的方法。 Any tips? 有小费吗?

Thanks in advance! 提前致谢!

You can reshape one of the arrays to a 2d array, then make use of numpy broadcasting : 您可以将其中一个数组整形为2d数组,然后使用numpy 广播

arr1[:,None] - arr2

arr1 = np.array([1,2])
arr2 = np.array([3,4,5])
​
arr1[:,None] - arr2
#array([[-2, -3, -4],
#       [-1, -2, -3]])

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

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