提取索引在 Python 中的正元素
Extracting positive elements with indices in Python
我有一个矩阵,N
。我想用它们的索引提取积极的元素。附上所需的输出。
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]])
期望的输出是
(0,1) - 9.65984145e-08
(1,2) - 4.88443157e-09
(1,4) - 1.46664353e-09 and so on
我想你在找 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)]
如果我们需要将它们分别放在两个单独的数组中,我们可以通过布尔掩码 N >= 0
获取值,然后将 np.where
数组转置为:
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]]
我有一个矩阵,N
。我想用它们的索引提取积极的元素。附上所需的输出。
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]])
期望的输出是
(0,1) - 9.65984145e-08
(1,2) - 4.88443157e-09
(1,4) - 1.46664353e-09 and so on
我想你在找 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)]
如果我们需要将它们分别放在两个单独的数组中,我们可以通过布尔掩码 N >= 0
获取值,然后将 np.where
数组转置为:
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]]