# Python Numpy.where() 函式

Sohaib Atiq 2023年1月30日

`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]
``````