Printing locations of non-zero elements of an array in Python
Question:
I have an array y
. I am identifying all nonzero elements with np.nonzero()
.
But, I want to print the output in a way as shown in the expected output.
import numpy as np
y=np.array([[ 0.0, -1.3e-08, 0.0 ],
[-1.3e-08, 0.0, 1.4e-9],
[0.0, 2.3e-7, 1.9e-6]])
Result=np.nonzero(y)
print(Result)
The current output is:
(array([0, 1, 1, 2, 2], dtype=int64), array([1, 0, 2, 1, 2], dtype=int64))
The expected output is:
array([[0,1],[1,0],[1,2],[2,1],[2,2]])
Answers:
You could use np.stack
import numpy as np
y=np.array([[ 0.0, -1.3e-08, 0.0 ],
[-1.3e-08, 0.0, 1.4e-9],
[0.0, 2.3e-7, 1.9e-6]])
Result=np.nonzero(y)
np.stack(Result, axis = -1)
Output
array([[0, 1],
[1, 0],
[1, 2],
[2, 1],
[2, 2]])
import numpy as np
y=np.array([[ 0.0, -1.3e-08, 0.0 ],
[-1.3e-08, 0.0, 1.4e-9],
[0.0, 2.3e-7, 1.9e-6]])
Result=np.nonzero(y)
print(np.array([[x,y] for x,y in zip(Result[0],Result[1])]))
I have an array y
. I am identifying all nonzero elements with np.nonzero()
.
But, I want to print the output in a way as shown in the expected output.
import numpy as np
y=np.array([[ 0.0, -1.3e-08, 0.0 ],
[-1.3e-08, 0.0, 1.4e-9],
[0.0, 2.3e-7, 1.9e-6]])
Result=np.nonzero(y)
print(Result)
The current output is:
(array([0, 1, 1, 2, 2], dtype=int64), array([1, 0, 2, 1, 2], dtype=int64))
The expected output is:
array([[0,1],[1,0],[1,2],[2,1],[2,2]])
You could use np.stack
import numpy as np
y=np.array([[ 0.0, -1.3e-08, 0.0 ],
[-1.3e-08, 0.0, 1.4e-9],
[0.0, 2.3e-7, 1.9e-6]])
Result=np.nonzero(y)
np.stack(Result, axis = -1)
Output
array([[0, 1],
[1, 0],
[1, 2],
[2, 1],
[2, 2]])
import numpy as np
y=np.array([[ 0.0, -1.3e-08, 0.0 ],
[-1.3e-08, 0.0, 1.4e-9],
[0.0, 2.3e-7, 1.9e-6]])
Result=np.nonzero(y)
print(np.array([[x,y] for x,y in zip(Result[0],Result[1])]))