Python 如何在二维数组中正确赋值?

Python 如何在二维数组中正确赋值?,python,graph,data-mining,Python,Graph,Data Mining,我试图为图中的每个节点子集分配一个热编码。 下面是我正在尝试的代码 import networkx as nx import numpy as np graph=nx.karate_club_graph() nodes=list(graph.nodes()) n=graph.number_of_nodes() subset_nodes=[1,2] for v in subset_nodes: y=nodes.index(v) prob_vec=np.zeros((n,n))

我试图为图中的每个节点子集分配一个热编码。 下面是我正在尝试的代码

import networkx as nx
import numpy as np
graph=nx.karate_club_graph()
nodes=list(graph.nodes())
n=graph.number_of_nodes()
subset_nodes=[1,2]

for v in subset_nodes:
    y=nodes.index(v)
    prob_vec=np.zeros((n,n))
    prob_vec[0][y]=1
    print(prob_vec)
我得到了这个结果

[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. 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.]]

I expect a matrix, with the subset nodes rows contains one hot encoding(1 value for each node in the subset node and others being zeros) like below:
[0. 1. 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.]]

任何帮助都将不胜感激

如果我理解您的意图,我认为您需要稍微调整代码。您当前正在打印每个循环并将prob_vec重置为0每个循环。我想你应该做些更像这样的事情:

import networkx as nx
import numpy as np
graph=nx.karate_club_graph()
nodes=list(graph.nodes())
n=graph.number_of_nodes()
subset_nodes=[1,2]

prob_vec=np.zeros((n,n))
for v in range(n):
  y = nodes.index(v)
  if y in subset_nodes:
    prob_vec[v][y]=1

print(prob_vec)
这将产生:

[[0. 0. 0. ... 0. 0. 0.]
 [0. 1. 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的行