This time I will bring you python How to use nonzero() in numpy, what are the precautions for using nonzero() in python numpy, the following is a practical case, one Get up and take a look.
nonzeroFunctionReturns the directory of nonzero elements.
The return value is a tuple, the two values are two dimensions respectively, and contain the directory values of non-zero elements in the corresponding dimensions.
import numpy as np A = np.mat([[0,1,2,3,4,3,2,1,0],[0,1,2,3,4,5,6,7,0]]) x = A.nonzero() #取出矩阵中的非零元素的坐标 print x #输出是一个元组,两个维度。一一对应, #返回非零元素在矩阵中的位置,前一个列表存放非零行坐标,后一个列表存放非零元素列坐标 #(array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]), array([1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7])) #放下来一一对应,即 #(array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]), #array([1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7])) # (0,1) (0,2).............................. (1,6) (1,7) 坐标上的元素都是非0的 print A[x],'\n' #取出矩阵中的非零元素 #[[1 2 3 4 3 2 1 1 2 3 4 5 6 7]] B = np.mat([[1,1,0,1,0,1,0,0,1],[0,1,1,0,0,0,1,1,1]]) print np.nonzero(B) # 与B.nonzero()等价
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to read and write txt files line by line in Python
How to implement the HMacMD5 encryption algorithm in Python
The above is the detailed content of How to use nonzero() in python numpy. For more information, please follow other related articles on the PHP Chinese website!