Numpy中bool式条件索引【Python琐碎知识点】

a  = np.arange(24).reshape(2,3,4)
a
"""
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
"""

[a>13]
"""
[array([[[False, False, False, False],
         [False, False, False, False],
         [False, False, False, False]],
 
        [[False, False,  True,  True],
         [ True,  True,  True,  True],
         [ True,  True,  True,  True]]])]
"""
# 单个条件时,返回一维数组,而非原来的shape
a[a>13]
# 两个条件时
a[(a>15)&(a<20)]

############ 输出内容 ########### 
array([14, 15, 16, 17, 18, 19, 20, 21, 22, 23])
array([16, 17, 18, 19])

需要提醒的是,如果仅限于条件判断,会返回原来相同shape的矩阵;而如果条件判断的shape矩阵作为索引的方式,则仅会返回一个一维数组。

猜你喜欢

转载自blog.csdn.net/m0_38052500/article/details/106858787