# 使用numpy.where函数出现的问题与思考

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

Return elements chosen from x or y depending on condition.

Note:
When only condition is provided, this function is a shorthand for `np.asarray(condition).nonzero()`. Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.

Parameters:

condition: array_like, bool

Where `True`, yield `x`, otherwise yield `y`.

x, y: array_like

Values from which to choose. `x`, `y` and `condition` need to be broadcastable to some shape.

Returns:

out: ndarray

An array with elements from `x` where condition is `True`, and elements from `y` elsewhere.

Notes:
If all the arrays are 1-D, `where` is equivalent to:
`[xv if c else yv for c, xv, yv in zip(condition, x, y)] `

``````# 一维数组
In [2]: a = np.arange(10)

In [3]: a
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [4]: np.where(a < 5, a, 10*a)
Out[4]: array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

``````
``````# 多维数组
In [5]: np.where([[True, False], [True, True]],
...:          [[1, 2], [3, 4]],
...:          [[9, 8], [7, 6]])
Out[5]:
array([[1, 8],
[3, 4]])
``````
``````# 传递的参数需要广播
In [6]: x, y = np.ogrid[:3, :4]

In [7]: x
Out[7]:
array([[0],
[1],
[2]])

In [8]: y
Out[8]: array([[0, 1, 2, 3]])

In [9]: x < y
Out[9]:
array([[False,  True,  True,  True],
[False, False,  True,  True],
[False, False, False,  True]])

In [10]: np.where(x < y, x, 10 + y)  # both x and 10+y are broadcast
Out[10]:
array([[10,  0,  0,  0],
[10, 11,  1,  1],
[10, 11, 12,  2]])

In [11]: a = np.array([[0, 1, 2],
...:               [0, 2, 4],
...:               [0, 3, 6]])

In [12]: np.where(a < 4, a, -1)  # -1 is broadcast
Out[12]:
array([[ 0,  1,  2],
[ 0,  2, -1],
[ 0,  3, -1]])

``````

THE END

)">