Numpy np.where

np.where seems to be an important function that need to be noticed.

Two examples to show its function.

  1. np.where(condition, x, y)

    1
    2
    3
    4
    5
    6
    7
    >>> import numpy as np
    >>> x = np.mat([1,2,3])
    >>> x
    matrix([[1, 2, 3]])
    >>> y = np.where(x > 1, 0, x)
    >>> y
    array([[1, 0, 0]])
  2. np.where(condition)

    1
    2
    3
    4
    5
    6
    7
    >>> import numpy as np
    >>> x = np.mat([1,2,3])
    >>> x
    matrix([[1, 2, 3]])
    >>> y = np.where(x > 1)
    >>> y
    (array([0, 0]), array([1, 2]))