numpy multiple slicing booleans

后端 未结 1 814

I\'m having trouble editing values in a numpy array

import numpy as np
foo = np.ones(10,10,2)

foo[row_criteria, col_criteria, 0] += 5
foo[row_criteria,:,0][         


        
相关标签:
1条回答
  • 2021-01-14 20:06

    You want:

    foo[np.ix_(row_criteria, col_criteria, [0])] += 5
    

    To understand how this works take this example:

    import numpy as np
    A = np.arange(25).reshape([5, 5])
    print A[[0, 2, 4], [0, 2, 4]]
    # [0, 12, 24]
    
    # The above example gives the the elements A[0, 0], A[2, 2], A[4, 4]
    # But what if I want the "outer product?" ie for [[0, 2, 4], [1, 3]] i want
    # A[0, 1], A[0, 3], A[2, 1], A[2, 3], A[4, 1], A[4, 3]
    print A[np.ix_([0, 2, 4], [1, 3])]
    # [[ 1  3]
    #  [11 13]
    #  [21 23]]
    

    The same thing works with boolean indexing. Also np.ix_ doesn't do anything really amazing, it just reshapes it's arguments so they can be broadcast against each other:

    i, j = np.ix_([0, 2, 4], [1, 3])
    print i.shape
    # (3, 1)
    print j.shape
    # (1, 2)
    
    0 讨论(0)
提交回复
热议问题