nonzero¶
- paddle. nonzero ( x, as_tuple=False ) [source]
-
Return a tensor containing the indices of all non-zero elements of the input tensor. If as_tuple is True, return a tuple of 1-D tensors, one for each dimension in input, each containing the indices (in that dimension) of all non-zero elements of input. Given a n-Dimensional input tensor with shape [x_1, x_2, …, x_n], If as_tuple is False, we can get a output tensor with shape [z, n], where z is the number of all non-zero elements in the input tensor. If as_tuple is True, we can get a 1-D tensor tuple of length n, and the shape of each 1-D tensor is [z, 1].
- Parameters
-
x (Tensor) – The input tensor variable.
as_tuple (bool, optional) – Return type, Tensor or tuple of Tensor.
- Returns
-
Tensor. The data type is int64.
Examples
import paddle x1 = paddle.to_tensor([[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]]) x2 = paddle.to_tensor([0.0, 1.0, 0.0, 3.0]) out_z1 = paddle.nonzero(x1) print(out_z1) #[[0 0] # [1 1] # [2 2]] out_z1_tuple = paddle.nonzero(x1, as_tuple=True) for out in out_z1_tuple: print(out) #[[0] # [1] # [2]] #[[0] # [1] # [2]] out_z2 = paddle.nonzero(x2) print(out_z2) #[[1] # [3]] out_z2_tuple = paddle.nonzero(x2, as_tuple=True) for out in out_z2_tuple: print(out) #[[1] # [3]]