test_array = np.asarray([[1,2,3],[4,5,6],[7,8,9]])
print(test_array>5)
输出结果是
[[False False False]
[False False True]
[ True True True]]
print(np.nonzero(test_array>5))
结果是
(array([1, 2, 2, 2], dtype=int32), array([2, 0, 1, 2], dtype=int32))
也就是生成一个tuple, 有两个数组构成。第一个数组是非零(false)的元素的行索引。第二个数组是非零(false)的元素的列索引。也就是(1,2),(2,0),(2,1),(2,2)位置对应的元素非零的
索引从第0列开始,如果只比较第1列上的值:
print(test_array[:,1]>5)
[False False True]
print(np.nonzero(test_array[:,1]>5))
(array([2], dtype=int32),)
nonzero返回的还是一个tuple元组,但是只有一个元素
比较常用的是有两个数组。 根据一个条件判断其中一个数组的元素, 根据判断结果,提取另一个数组的元素。这两个数组可以是相同的。
test_array = np.asarray([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
index_array = np.asarray([[0, 2, 0],
[0, 0, 0],
[0, 2, 2]])
例子A:找到index_array中所有第1列不为0的行,找到第0行和第2行,
从test_array中提取对应的行。
condition_index= np.nonzero( index_array [:,1] !=0 ) print(condition_index) print( test_array[condition_index] )
输出:(array([0, 2], dtype=int32),)
[[1 2 3]
[7 8 9]]
另一个例子:找到index_array中所有不为0的元素,找到(0,1),(2,1),(2,2). 从test_array中提取对应行列的元素
condition_index= np.nonzero( index_array != 0 ) print(condition_index) print( test_array[condition_index] )
输出:(array([0, 2, 2], dtype=int32), array([1, 1, 2], dtype=int32))
[2 8 9]