Difference between two numpy arrays in python

前端 未结 2 2101
悲哀的现实
悲哀的现实 2021-01-03 17:41

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 the

相关标签:
2条回答
  • 2021-01-03 17:59

    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])
    
    0 讨论(0)
  • 2021-01-03 18:23

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

    diffs = array1 - array2
    

    I get:

    diffs == array([ 0.1,  0.2,  0.3])
    
    0 讨论(0)
提交回复
热议问题