数组中的值出现在另一个数组中的索引
Indices where values in array occur in another array
我有这个数组:
n=nodes of the graph
a=np.random.choice(n,size=3)
prob=np.zeros((1,n))
如何根据节点的索引将 a
中的节点分配给 prob
?
我有这个代码:
for k in a:
m=nodes.index(k)
b=np.zeros((1,n))
b[0][m]=1
here the results
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
但对我来说,我想要这个结果
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
任何帮助将不胜感激
您要在每次迭代中重置 b
,您需要在 for
循环之前初始化 b
,然后 然后 更新 b
,每个结果为 m
。还要注意 b
只需要 1 个轴。让我们考虑例如以下节点列表,以及我们将用于查找 nodes
:
中的位置的节点数组 a
nodes = [5,12,6,1,3,9,4,8,2,45]
a = np.array([5, 9, 8, 4])
调整你的方法,你会:
b=np.zeros(len(nodes))
for k in a:
m=nodes.index(k)
b[m]=1
print(b)
# array([1., 0., 0., 0., 0., 1., 1., 1., 0., 0.])
但是请注意,这具有不必要的 O(len(nodes)*len(a))
复杂性。更好的方法是构建一个查找 table 映射值到 nodes
中的位置,并分配给 b
为:
d = {v:k for k,v in enumerate(nodes)}
b=np.zeros(len(nodes))
for k in a:
b[d[k]] = 1
print(b)
#array([1., 0., 0., 0., 0., 1., 1., 1., 0., 0.])
此外,由于您使用的是 numpy,我们可以使用 np.searchsorted
和 np.bincount
来加快上述速度:
nodes = np.array(nodes)
nodes_s = nodes.argsort()
s = np.searchsorted(nodes[nodes_s],a)
b = np.bincount(nodes_s[s], minlength=len(nodes))
print(b)
# array([1, 0, 0, 0, 0, 1, 1, 1, 0, 0])
我有这个数组:
n=nodes of the graph
a=np.random.choice(n,size=3)
prob=np.zeros((1,n))
如何根据节点的索引将 a
中的节点分配给 prob
?
我有这个代码:
for k in a:
m=nodes.index(k)
b=np.zeros((1,n))
b[0][m]=1
here the results
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
但对我来说,我想要这个结果
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
任何帮助将不胜感激
您要在每次迭代中重置 b
,您需要在 for
循环之前初始化 b
,然后 然后 更新 b
,每个结果为 m
。还要注意 b
只需要 1 个轴。让我们考虑例如以下节点列表,以及我们将用于查找 nodes
:
a
nodes = [5,12,6,1,3,9,4,8,2,45]
a = np.array([5, 9, 8, 4])
调整你的方法,你会:
b=np.zeros(len(nodes))
for k in a:
m=nodes.index(k)
b[m]=1
print(b)
# array([1., 0., 0., 0., 0., 1., 1., 1., 0., 0.])
但是请注意,这具有不必要的 O(len(nodes)*len(a))
复杂性。更好的方法是构建一个查找 table 映射值到 nodes
中的位置,并分配给 b
为:
d = {v:k for k,v in enumerate(nodes)}
b=np.zeros(len(nodes))
for k in a:
b[d[k]] = 1
print(b)
#array([1., 0., 0., 0., 0., 1., 1., 1., 0., 0.])
此外,由于您使用的是 numpy,我们可以使用 np.searchsorted
和 np.bincount
来加快上述速度:
nodes = np.array(nodes)
nodes_s = nodes.argsort()
s = np.searchsorted(nodes[nodes_s],a)
b = np.bincount(nodes_s[s], minlength=len(nodes))
print(b)
# array([1, 0, 0, 0, 0, 1, 1, 1, 0, 0])