[python numpy] numpy布尔值索引 数组索引

更详细见:https://blog.csdn.net/Lord_sh/article/details/92653790

>>> x = np.arange(0, 16).reshape(4, 4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> idx = [[1,0,0,0],[0,1,0,0],[0,1,0,0],[0,0,0,1]]
>>> idx
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1]]
>>> idx = np.array(idx)
>>> idx
array([[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 0, 1]])
>>> idx.shape
(4, 4)
# 其实就是行索引
>>> x[idx]
array([[[4, 5, 6, 7],
        [0, 1, 2, 3],
        [0, 1, 2, 3],
        [0, 1, 2, 3]],

       [[0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 1, 2, 3],
        [0, 1, 2, 3]],

       [[0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 1, 2, 3],
        [0, 1, 2, 3]],

       [[0, 1, 2, 3],
        [0, 1, 2, 3],
        [0, 1, 2, 3],
        [4, 5, 6, 7]]])
//布尔索引
>>> x[idx==1]
array([ 0,  5,  9, 15])
>>> x.shape
(4, 4)
>>> x[idx].shape
(4, 4, 4)
>>> x[idx==1].shape
(4,)

 

你可能感兴趣的:(python)