# Python Numpy.where() 函数

`numpy.where()` 函数在没有给出 `x``y` 的情况下，生成符合输入条件的数组索引；或者根据给定的条件从 `x``y` 中生成数组元素。

## `numpy.where()` 语法

``````numpy.where(condition,[x,y])
``````

### 参数

`condition` array_like, `True``False`

`x,y` 返回值产生的数组

## 示例代码：`numpy.where()`, 没有 `[x, y]` 输入

``````import numpy as np

m = np.array([1,2,3,4,5])

n = np.where(m > 3)

print(n)
``````

``````(array([3, 4], dtype=int64),)
``````

## 示例代码：`numpy.where()` 与 1-D 数组的关系

``````import numpy as np

m = np.where([True, False, True], [1,2,3], [4, 5, 6])

print(m)
``````

``````[1 5 3]
``````

## 示例代码：`numpy.where()` 与二维数组的关系

``````import numpy as np

x = np.array([[10, 20, 30],
[3, 50, 5]])
y = np.array([[70, 80, 90],
[100, 110, 120]])
condition = np.where(x>20,x,y)

print("Input array :")
print(x)
print(y)
print("Output array with condition applied:")
print(condition)
``````

``````Input array :
[[10 20 30]
[ 3 50  5]]
[[ 70  80  90]
[100 110 120]]
Output array with condition applied:
[[ 70  80  30]
[100  50 120]]
``````

``````import numpy as np

m = np.where([[True, False, True],
[False, True, False]],
[[1,2,3],
[4, 5, 6]],
[[7,8,9],
[10, 11, 12]])

print(m)
``````

``````[[ 1  8  3]
[10  5 12]]
``````

## 示例代码：`numpy.where()` 有多个条件

``````import numpy as np

m = np.array([1,2,3,4,5])

n = np.where((m > 1) & (m < 5), m, 0)

print(n)
``````

``````[0 2 3 4 0]
``````

``````import numpy as np

m = np.array([1,2,3,4,5])

n = np.where((m < 2) | (m > 4), m, 0)

print(n)
``````

``````[1 0 0 0 5]
``````