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!
This is pretty simple with numpy
, just subtract the arrays:
diffs = array1 - array2
I get:
diffs == array([ 0.1, 0.2, 0.3])
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