When developing with Numpy, I encountered a problem that required each element of a Numpy array to be compared with a number, returning a logical array. We can use arrays and numbers directly in Numpy calculations, very convenient. When I tried to use the broadcast mechanism to deal with the array and number comparison problem, I found that the broadcast mechanism also works. Here is the test code:

  • Example 1, comparing the size of a two-dimensional array with a number:
Import Numpy as NP A = np.linspace(1,12,12). 0 0 Print (" A is /n", a) b = 3 C = a > B print(" C is /n", c)Copy the code

Result: C is broadcast as a 3×4 array with each element of 3

a is [[ 1. 2. 3. 4.] [ 5. 6. 7. 8.] [ 9. 10. 11. 12.]] c is [[False False False True] [ True True True True] [ True True  True True]]Copy the code
  • Example 2: Compare the size of a two-dimensional array with that of a one-dimensional array:
0 Import Numpy as NP A = np.linspace(1,12,12). 0 Print (" A is \n", a) print("d is \n", 0 d) e = a > d print("e is \n",e )Copy the code

Results: It is shown that D is broadcast as a two-dimensional array of 3×4 with column vectors of [2. 3. 4.

a is
 [[ 1.  2.  3.]
 [ 4.  5.  6.]
 [ 7.  8.  9.]
 [10. 11. 12.]]
d is
 [2. 3. 4.]
e is
 [[False False False]
 [ True  True  True]
 [ True  True  True]
 [ True  True  True]]
Copy the code

Other radio content can refer to this blog: blog.csdn.net/xiaosongshi…