numpy.where用法

函数原型:numpy.where(condition[, x, y])

 

参数介绍:condition:类似于矩阵,布尔值。当其值为True时,从x中选定值,否则,从y中选择值

       x,y:类似于矩阵,可选参数。根据condition的值来决定从x或y中取值

 

返回值:ndarray或者ndarrays的元组 

    如果x和y都被指定,则输出矩阵的元素组成为,当某个位置的condition为True时, 该位置用相应的x值填充,若为False,则用相应的y值填充

    如果只给出了condition,而未指定x和y,则返回元组condition.nonzero()       

    (condition.nonzero()的作用是返回condition中值不为0的元素的索引,以元组的形式返回,元组由轴组成,每个轴的内容为该轴上值不为零的元素的索引)

 

情况1:x和y都被指定
1 import numpy as np
2 
3 np.where([[False, False], [True, True]],    # codition: [[False, False], [True, True]]
4                [[1, 2], [3, 4]],            # x: [[1, 2], [3, 4]]
5                [[9, 8], [7, 6]])            # y: [[9, 8], [7, 6]]
6 
7 # 输出为:
8 # [[9 8]                                    # 对于codition中,位置(0, 0)和位置(0, 1)的值为False,所以该位置的输出对应于y的相应位置的值[9 8]
9 #  [3 4]]                                   # codition中,位置(1, 0)和位置(1, 1)的值为True,所以该位置的输出对应于x的相应位置的值[3 4]

 

情况2:只给出condition,未指定x和y

1 import numpy as np
2 
3 print(np.where([[0, 1], [1, 1]]))         # 未指定x和y,只给出了condition,此时以元组的形式返回condition中非零元素的索引
4 
5 # 输出为:
6 # (array([0, 1, 1], dtype=int32),         # condition中,位置(0, 1), (1, 0), (1, 1)的值非零,对于轴0,非零值的索引为[0, 1, 1]
7 # array([1, 0, 1], dtype=int32))          # 对于轴1,非零值的索引为[1, 0, 1],元组的元素由两个轴组成,所以为([0, 1, 1], [1, 0, 1])

 

文档链接:https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
 
posted @ 2018-08-27 16:11  Latuper  阅读(735)  评论(0编辑  收藏  举报