The conditional logic operation as an array (WHERE)

This chapter will explain numpy.where function.

He is a vectorized version of a triplet of expressions.

A triplet of expressions: x if condition else y

import numpy as np
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])

When the element is in the cond is True, we take the corresponding element values ​​xarr, whereas the elements having yarr, the list can be accomplished by deriving the formula below

result = [(x if c else y) for x,y,c in zip(xarr, yarr, cond)]
print result

结果
[1.1, 2.2, 1.3, 1.4, 2.5]

This creates a number of problems, first of all if the array is large, it can be slow, because all the work is done through the interpretation of Python code interpreter, and secondly, it is a multi-dimensional array, can not be worked. The use np.where, it can very easily do so.

result = np.where(cond, xarr, yarr)
print(result)

结果
[1.1, 2.2, 1.3, 1.4, 2.5]

where the second and third parameters do not need to be an array, which may be scalars. where a typical use of data analysis is to generate a new array according to an array.

For example: Assuming a normal distribution of the data matrix I have a randomly generated, and you want to have become one of the positive number 2, all have become negative -2, where it is easy to implement using

arr = np.random.randn(4,4)
print(arr)
print('-----------')
print(np.where(arr>0, 2, -2))
print('---------')
print(np.where(arr > 0, 2 , arr))


结果
[[-1.36253267  0.7440669   0.64946862  0.36891392]
 [-0.01551911  0.01003852  2.32228195 -0.17199506]
 [ 0.46897204 -0.15731851 -0.53239796 -0.56446061]
 [-0.55566614 -0.27882886 -0.12773451 -0.15585518]]
-----------
[[-2  2  2  2]
 [-2  2  2 -2]
 [ 2 -2 -2 -2]
 [-2 -2 -2 -2]]
---------
[[-1.36253267  2.          2.          2.        ]
 [-0.01551911  2.          2.         -0.17199506]
 [ 2.         -0.15731851 -0.53239796 -0.56446061]
 [-0.55566614 -0.27882886 -0.12773451 -0.15585518]]

As can be seen, the third parameter can be written in the original array, the elements equivalent to less than 0 with the value corresponding to the position of the original array transducer, that is not treated.

to sum up:

Array passed to np.where may be either the same size of the array may be a scalar

Guess you like

Origin www.cnblogs.com/chanyuli/p/11762427.html