python中两个numpy数组的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21516089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between two numpy arrays in python
提问by user3263816
I have two arrays, for example:
我有两个数组,例如:
array1=numpy.array([1.1, 2.2, 3.3])
array2=numpy.array([1, 2, 3])
How can I find the difference between these two arrays in Python, to give:
如何在 Python 中找到这两个数组之间的区别,以给出:
[0.1, 0.2, 0.3]
As an array as well?
也作为数组?
Sorry if this is an amateur question - but any help would be greatly appreciated!
对不起,如果这是一个业余问题 - 但任何帮助将不胜感激!
回答by jonrsharpe
This is pretty simple with numpy, just subtract the arrays:
这很简单numpy,只需减去数组:
diffs = array1 - array2
I get:
我得到:
diffs == array([ 0.1, 0.2, 0.3])
回答by mark jay
You can also use numpy.subtract
你也可以使用 numpy.subtract
It has the advantage over the difference operator, -, that you do not have to transform the sequences(list or tuples) into a numpy arrays— you save the two commands:
与差分运算符 相比,它的优势-在于您不必将序列(列表或元组)转换为numpy 数组——您保存了两个命令:
array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])
Example:(Python 3.5)
示例:(Python 3.5)
import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)
which gives you
这给了你
the difference = [ 0.1 0.2 0.3]
Remember, however, that if you try to subtract sequences (lists or tuples) with the -operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays
但是,请记住,如果您尝试使用运算-符减去序列(列表或元组),则会出现错误。在这种情况下,您需要上述命令来转换numpy 数组中的序列
Wrong Code:
错误代码:
print([1.1, 2.2, 3.3] - [1, 2, 3])

