Basics of numpy where function, what does it do to the array?

前端 未结 1 1903
鱼传尺愫
鱼传尺愫 2021-01-14 15:53

I have seen the post Difference between nonzero(a), where(a) and argwhere(a). When to use which? and I don\'t really understand the use of the where function from numpy modu

相关标签:
1条回答
  • 2021-01-14 16:55

    np.where returns indices where a given condition is met. In your case, you're asking for the indices where the value in Z is not 0 (e.g. Python considers any non-0 value as True). Which for Z results in:

    (0, 0) # top left
    (0, 2) # third element in the first row
    (0, 3) # fourth element in the first row
    (1, 3) # fourth element in the second row
    ...    # and so on
    

    np.where starts to make sense in the following scenarios:

    a = np.arange(10)
    np.where(a > 5) # give me all indices where the value of a is bigger than 5
    # a > 5 is a boolean mask like [False, False, ..., True, True, True]
    # (array([6, 7, 8, 9], dtype=int64),)
    

    Hope that helps.

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