Difference between two numpy arrays in python

喜欢而已 提交于 2019-12-09 02:27:38

问题


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:

[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!


回答1:


This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])



回答2:


You can also use 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:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (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

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])


来源:https://stackoverflow.com/questions/21516089/difference-between-two-numpy-arrays-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!