where()函数是numpy模块中的一个函数,它的语法如下:
where(condition, [x, y])
有点类似python中的三目运算符:
x = a if condition else b
[x,y]是可选参数,举个例子:
import numpy as np
arr = np.random.randint(0,10,(3,5))
print (arr)
np.where(arr<5)
[[8 6 7 8 8]
[1 7 1 8 6]
[8 9 7 3 6]]
(array([1, 1, 2], dtype=int64), array([0, 2, 3], dtype=int64))
现在加上可选条件,让数组中大于5的数字全部变成5
import numpy as np
arr = np.random.randint(0,10,(3,5))
print (arr)
np.where(arr>5,5,arr)
[[3 3 0 2 1]
[2 3 0 2 3]
[6 1 0 6 4]]
…
array([[3, 3, 0, 2, 1],
[2, 3, 0, 2, 3],
[5, 1, 0, 5, 4]])
本文介绍了numpy的where()函数,该函数类似于Python的三目运算符。通过示例展示了如何使用where()来定位数组中大于5的元素,并将它们替换为5。
2380

被折叠的 条评论
为什么被折叠?



