简体   繁体   English

numpy数组中的元素减法

[英]Elementwise subtraction in numpy arrays

I have two numpy arrays of different dimensions: x.shape = (1,1,M) and Y.shape = (N,N) .我有两个不同维度的 numpy 数组: x.shape = (1,1,M)Y.shape = (N,N) How do I perform Z = x - Y efficiently in python, such that Z.shape = (N,N,M) , where - is an elementwise subtraction operation.我如何在 python 中有效地执行Z = x - Y ,这样Z.shape = (N,N,M) ,其中-是元素减法运算。

For example, M=10例如, M=10

x = array([[[1, 2, 3, 4, 5 , 6, 7, 8, 9, 10]]])

and N=8并且N=8

Y = array([[11, 12, 13, 14, 15, 16, 17, 18],
           [21, 22, 23, 24, 25, 26, 27, 28],
           [31, 32, 33, 34, 35, 36, 37, 38],
           [41, 42, 43, 44, 45, 46, 47, 48],
           [51, 52, 53, 54, 55, 56, 57, 58],
           [61, 62, 63, 64, 65, 66, 67, 68],
           [71, 72, 73, 74, 75, 76, 77, 78],
           [81, 82, 83, 84, 85, 86, 87, 88]])

Now the idea is to get a Z such that现在的想法是得到一个Z使得

Z[:,:,0] = array([[1-11, 1-12, 1-13, 1-14, 1-15, 1-16, 1-17, 1-18],
                  [1-21, 1-22, 1-23, 1-24, 1-25, 1-26, 1-27, 1-28],
                  [1-31, 1-32, 1-33, 1-34, 1-35, 1-36, 1-37, 1-38],
                  [1-41, 1-42, 1-43, 1-44, 1-45, 1-46, 1-47, 1-48],
                  [1-51, 1-52, 1-53, 1-54, 1-55, 1-56, 1-57, 1-58],
                  [1-61, 1-62, 1-63, 1-64, 1-65, 1-66, 1-67, 1-68],
                  [1-71, 1-72, 1-73, 1-74, 1-75, 1-76, 1-77, 1-78],
                  [1-81, 1-82, 1-83, 1-84, 1-85, 1-86, 1-87, 1-88]])

and

Z[:,:,9] = array([[10-11, 10-12, 10-13, 10-14, 10-15, 10-16, 10-17, 10-18],
                  [10-21, 10-22, 10-23, 10-24, 10-25, 10-26, 10-27, 10-28],
                  [10-31, 10-32, 10-33, 10-34, 10-35, 10-36, 10-37, 10-38],
                  [10-41, 10-42, 10-43, 10-44, 10-45, 10-46, 10-47, 10-48],
                  [10-51, 10-52, 10-53, 10-54, 10-55, 10-56, 10-57, 10-58],
                  [10-61, 10-62, 10-63, 10-64, 10-65, 10-66, 10-67, 10-68],
                  [10-71, 10-72, 10-73, 10-74, 10-75, 10-76, 10-77, 10-78],
                  [10-81, 10-82, 10-83, 10-84, 10-85, 10-86, 10-87, 10-88]])

and so on.等等。

It is easy to do in MATLAB using just - operation.在 MATLAB 中使用 just -操作很容易做到。 But Python does not support it.但是 Python 不支持它。

The answer is: use different shape of y :答案是:使用不同形状的y

>>> y = y.reshape((8, 8, 1))
>>> (x-y).shape
(8, 8, 10)

This is a vizualization for better understanding with smaller dimensions:这是一个可视化,以更好地理解较小的维度:

在此处输入图片说明

You can compute your result without explicit creation of a reshaped array, but using Numpy broadcasting.您可以在不显式创建重构数组的情况下计算结果,而是使用Numpy广播。

The key to success is to add a new dimension to Y , using np.newaxis :成功的关键是使用np.newaxisY添加一个新维度:

Z = x - Y[:, :, np.newaxis]

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

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