I have a matrix, N
. I would like to extract positive elements with their indices. The desired output is attached.
import numpy as np
from numpy import nan
N=np.array([[ nan, 9.65984145e-08, nan,
nan, nan, nan,
nan],
[-6.35107511e-09, nan, 4.88443157e-09,
nan, 1.46664353e-09, nan,
nan],
[ nan, -1.38022162e-08, nan,
1.37404097e-08, nan, 6.18065590e-11,
nan],
[ nan, nan, -7.82145993e-10,
nan, nan, nan,
7.82145990e-10],
[ nan, -3.98567193e-09, nan,
nan, nan, 3.98567195e-09,
nan],
[ nan, nan, -5.47197743e-11,
nan, -3.66918072e-09, nan,
3.72390048e-09],
[ nan, nan, nan,
-3.39767791e-09, nan, -1.04008985e-09,
nan]])
The desired output is
(0,1) - 9.65984145e-08
(1,2) - 4.88443157e-09
(1,4) - 1.46664353e-09 and so on
CodePudding user response:
I think you are looking for np.where()
:
idx = np.where(N > 0)
>>> list(zip(*idx, N[idx]))
[(0, 1, 9.65984145e-08),
(1, 2, 4.88443157e-09),
(1, 4, 1.46664353e-09),
(2, 3, 1.37404097e-08),
(2, 5, 6.1806559e-11),
(3, 6, 7.8214599e-10),
(4, 5, 3.98567195e-09),
(5, 6, 3.72390048e-09)]
CodePudding user response:
If we need them separately in two separate arrays, we can get values by Boolean mask N >= 0
and then by transposing np.where
array as:
values = N[N >= 0]
# [9.65984145e-08 4.88443157e-09 1.46664353e-09 1.37404097e-08 6.18065590e-11 7.82145990e-10 3.98567195e-09 3.72390048e-09]
indices = np.array(np.where(N >= 0)).T
# [[0 1]
# [1 2]
# [1 4]
# [2 3]
# [2 5]
# [3 6]
# [4 5]
# [5 6]]