Python: Np.where Ternary Operator

through the use of np.where It can perform more complex operations

np.where ()

score = np.random.randint(40, 100, (10, 5))
score
array([[51, 81, 74, 58, 56],
       [94, 79, 51, 92, 94],
       [84, 79, 54, 87, 81],
       [52, 53, 69, 83, 73],
       [42, 68, 67, 50, 55],
       [45, 85, 58, 72, 61],
       [78, 63, 80, 99, 95],
       [66, 45, 51, 89, 48],
       [46, 63, 78, 43, 85],
       [93, 69, 83, 91, 96]])

temp = score[:4, :4]
# Judgment of the top four students, the first four courses, the grade greater than 60 set to 1, otherwise 0
np.where(temp > 60, 1, 0)
array([[0, 1, 1, 0],
       [1, 1, 0, 1],
       [1, 1, 0, 1],
       [0, 0, 1, 1]])

Compound logic needs combination np.logical_ And and np.logical_ Or use

# determine the first four students, the first four courses, the results of greater than 60 and less than 90 for 1, otherwise 0
np.where(np.logical_and(temp > 60, temp < 90), 1, 0) # greater than 60, less than 90 show 1
array([[0, 1, 1, 0],
       [0, 1, 0, 0],
       [1, 1, 0, 1],
       [0, 0, 1, 1]])

# determine the first four students, the first four courses, the grades in greater than 90 or less than 60 for 1, otherwise 0
np.where(np.logical_or(temp <60, temp > 90), 1, 0) less than 60 greater than 90 show 1
array([[1, 0, 0, 1],
       [1, 0, 1, 1],
       [0, 0, 1, 0],
       [1, 1, 0, 0]])


Read More: