where method nesting in numpy

  • 2021-01-19 22:19:06
  • OfStack

As with the for loop 1, the where methods in numpy can implement nesting. This is a nice way to simplify the logic of nested matrices.

Let's say I have a matrix, and I want to change the elements that are less than 0 to negative 1, the elements that are greater than 0 to 1, and I don't want to change the elements that are equal to 0.

So, the corresponding code demonstration is as follows:


#!/usr/bin/python
 
import numpy as np
 
data = np.random.randn(4,5)
data1 =np.where(data > 0,1,
np.where(data <0,-1,0))
print("datavalue:")
print(data)
print("data1value:")
print(data1)

The execution result of the program is as follows:


In [3]: %runpython_exp04.py

data value:

[[-2.06262429 0.94548656 -0.29458562 0.82657 -1.08587439]
 [-0.67416161 0.77247191 0.60330603 0.73694198 -0.63761278]
 [ 0.24887356 -0.27086027 0.34312363 0.727303 0.72741593]
 [-0.48973095 -0.33185631 -1.23341695 0.13569267 2.06881178]]

data1 value:

[[-1 1 -1 1-1]
 [-1 1 1 1 -1]
 [ 1 -1 1 1 1]
 [-1 -1 -1 1 1]]

This usage is not only cleaner than the code achieved by simply iterating through a compound loop, but also has a significant advantage in terms of execution efficiency. Most of the time, the vectorization of computation is to speed up the execution of the entire program.


Related articles: