Numpy where syntax from docs

后端 未结 3 1604
我寻月下人不归
我寻月下人不归 2020-12-12 04:44

Trying to teach myself some python and I am super confused from the docs what the where function does. Can somebody explain the example from the documentation below step by

相关标签:
3条回答
  • 2020-12-12 05:26

    I think it becomes pretty clear when you add linebreaks to arrange the inputs to look like matrices:

    np.where( # First argument
             [[True, False], 
              [True, True]],
              # Second argument
              [[1, 2], 
               [3, 4]],
              # Third argument
              [[9, 8], 
               [7, 6]])
    

    You can see the first argument as a mask that determines from which of the two following inputs elements should be taken.

    The result

    array([[1, 8],
           [3, 4]])
    

    contains elements from the second argument wherever the mask is True and elements from the third argument where it is False.

    0 讨论(0)
  • 2020-12-12 05:30

    The basic syntax is np.where(x, a, b) Wherever x is true, take that element of a, and wherever it's false, take an element of b. It's equivalent to something like this:

    x = . . [[1, 0], [1, 1]]), not x =[[0, 1], [0, 0 ]]

    array([[1, 2], [3, 4]]) + array([[7, 8], [9, 10]])

    array([[1, 0], [3, 4]]) + array([[0, 8], [0, 0 ]]) = array([[1, 8], [3, 4]])

    0 讨论(0)
  • 2020-12-12 05:39

    Basically used as follows:

    np.where(condition, value if condition is True, value if condition is False)
    

    In this case:

    condition is [[True, False], [True, True]]

    value if condition is True is [[1, 2], [3, 4]].

    value if condition is False is [[9, 8], [7, 6]].

    The final result of array([[1, 8], [3, 4]]) is equal to the array from 'value if condition is True', except for the one location in condition where it is False. In this case, the value of 8 comes from the second array.

    0 讨论(0)
提交回复
热议问题