Numpy之where函数
一、函数说明
numpy.where(condition[, x, y])
各个参数意义:
- condition:类似数组的对象,布尔值
- x, y:类似数组的对象,给出值的地方,如果 condition 为 True,从 x 中选取值,condition 为 False,从 y 中选取值。
- 有返回值,返回一个满足条件时取x中对应的值,不满足条件时取 y 中对应值的数组。
- 注意:这里的 condition,x,y只是为了表示以及说明时的必要,并不是真正意义上的关键字。
二、用法
np.where 函数是三元表达式 x if condition else y 的向量化版本,它有两种用法:
np.where(condition,x,y) 当where内有三个参数时,第一个参数表示条件,当条件成立时where方法返回x,当条件不成立时where返回y
np.where(condition) 当where内只有一个参数时,那个参数表示条件,当条件成立时,where返回的是每个符合condition条件元素的坐标,返回的是以元组的形式
示例1
有两个数值数组和一个布尔数组。当布尔数组为True 时,输出 xarr 的值,否则输出 yarr 的值
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])
carr = np.array([True, False, True, True, False])
result = np.where(carr, xarr, yarr)
print(result)
[1.1 2.2 1.3 1.4 2.5]
示例2
np.where的第二个和第三个参数不需要是数组,也可以是标量。where在数据分析中的一个典型用法是根据一个数组来生成一个新的数组。
假设有一个随机生成的矩阵数据,并且想将其中的正值都替换为2,负值都替换为-2
import numpy as np
arr = np.random.randn(4, 4)
print(f'arr is {arr}')
brr = np.where(arr > 0, 2, -2)
print(f'brr is {brr}')
arr is [[ 0.25269699 0.65883562 -0.25147374 -1.39408775]
[-0.53498966 -0.97424514 -1.13900344 0.53646289]
[ 1.51928884 0.80805854 -0.82968494 0.82861136]
[ 0.09549692 0.59623201 0.50521756 1.648034 ]]
brr is [[ 2 2 -2 -2]
[-2 -2 -2 2]
[ 2 2 -2 2]
[ 2 2 2 2]]