python中np.where()的使用方法

np.where有两种用法

    1. np.where(condition, x, y) 当 where 内有三个参数时,第一个参数表示条件,当条件成立时 where 方法返回 x,当条件不成立时 where 返回 y
    1. np.where(condition) 当 where 内只有一个参数时,那个参数表示条件,当条件成立时,where 返回的是每个符合 condition 条件元素的坐标,返回的是以元组的形式
    1. 多条件时 condition,& 表示与,|表示或。如 a = np.where((0<a)&(a<5), x, y),当 0<a 与 a<5 满足时,返回x的值,当 0<a 与 a<5 不满足时,返回 y 的值。注意 x, y 必须和 a 保持相同尺寸。

代码示例:
用法一:三个参数

>>> import numpy as np

>>> x = np.random.randn(4, 4)
Out[4]: 
array([[-1.07932656,  0.48820426,  0.27014549,  0.43823363],
       [ 0.28400645,  0.89720027,  1.6945324 , -1.41739129],
       [ 0.55640566, -0.99401836, -1.58491355,  0.90241023],
       [-0.14711914, -1.21307824, -0.0509225 ,  1.39018565]])
>>> np.where(x > 0, 2, -2)
Out[5]: 
array([[-2,  2,  2,  2],
       [ 2,  2,  2, -2],
       [ 2, -2, -2,  2],
       [-2, -2, -2,  2]])

用法二: 一个参数

>>> a = np.array([2,4,6,8,10])
#只有一个参数表示条件的时候
>>> np.where(a > 5)

Out[5]: (array([2, 3, 4], dtype=int64),)

用法3:多条件

# 满足 (data>= 0) & (data<=2),则返回np.ones_like(data),否则返回 np.zeros_like(data)
>>> import numpy as np

>>> data = np.array([[0, 2, 0], 
				     [3, 1, 2],
                     [0, 4, 0]])
>>> new_data = np.where((data>= 0) & (data<=2), np.ones_like(data), np.zeros_like(data))
>>> print(new_data)
Out[6]:
[[1 1 1]
 [0 1 1]
 [1 0 1]]

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年9月13日
下一篇 2023年9月13日

相关推荐