당신이 원하는 것은 가능합니다. 귀하의 데이터를 CSV 파일에 저장했습니다 - 노드 이름 다음에 ,
을 추가했으며 모든 공백을 제거했음을 유의하십시오.
Name1,2-s2.0-84905590088,2-s2.0-84901477890
Name2,2-s2.0-84941169876
Name3,2-s2.0-84958012773
Name4,2-s2.0-84960796474
Name5,2-s2.0-84945302996,2-s2.0-84953281823,2-s2.0-84944268402,2-s2.0-84949478621,2-s2.0-84947281259,2-s2.0-84947759580,2-s2.0-84945265895,2-s2.0-84945247800,2-s2.0-84946541351,2-s2.0-84946051072,2-s2.0-84942573284,2-s2.0-84942280140,2-s2.0-84937715425,2-s2.0-84943751990,2-s2.0-84957729558,2-s2.0-84938844501,2-s2.0-84934761065
Name6,2-s2.0-84908333808
Name7,2-s2.0-84925879816
Name8,2-s2.0-84940447040,2-s2.0-84949534001
Name9,2-s2.0-84899915556,2-s2.0-84922392381,2-s2.0-84905079505,2-s2.0-84940931972,2-s2.0-84893682063,2-s2.0-84954285577,2-s2.0-84934934228,2-s2.0-84926624187
Name10,2-s2.0-84907065810
한 관찰 : 당신은 Name5
은 가장자리가 많이있을 것입니다하지만, 그 속성은 고유 말한다. 또한 데이터로 코드를 실행하면 모든 속성이 고유하므로 그래프에 모서리가 없습니다.
나는 각 속성의 처음 12 자만 사용할 수 있도록 데이터를 트위 킹했습니다 (줄 번호 new_attributes = [x[:12] for x in new_attributes]
). 그렇게하면 일치하는 속성을 얻을 수 있습니다.
이제 코드 : I 그래프 (및 해당 속성) 나는 가장자리를 추가에서 현재 노드에 근거 그래프에 (그 속성과) 노드를 추가하고 각 CSV의 행에 대해
import networkx as nx
import csv
G = nx.Graph()
with open('data.csv') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for row in csv_reader:
new_node = row[0] # first element in row
new_attributes = row[1:] # whole row except the first element
new_attributes = [x[:12] for x in new_attributes] # remove this for your data!
# add the node and its attributes to the graph
G.add_node(new_node, my_attributes=new_attributes) # attributes are stored as a list
# add edges based on existing nodes
for node, attrs in G.nodes(data=True):
# skip node we just added
if node != new_node:
for attr in attrs['my_attributes']:
# check if any of the attributes for `node` are also in the `new_attributes` list
if attr in new_attributes:
G.add_edge(node, new_node)
for edge in G.edges():
print('EDGE:', edge, '| COMMON ATTRIBUTES:', set(G.node[edge[0]]['my_attributes']) & set(G.node[edge[1]]['my_attributes']))
. 노드 속성은 목록에 저장되며 my_attributes
키를 사용하여 액세스 할 수 있습니다. 마지막으로 특정 가장자리의 노드에 대해 일치하는 특성으로 가장자리를 인쇄합니다 (두 특성의 목록을 얻기 위해 set
및 &
을 사용합니다). tweeked 데이터
출력 :
EDGE: ('Name5', 'Name9') | COMMON ATTRIBUTES: {'2-s2.0-84934'}
EDGE: ('Name5', 'Name8') | COMMON ATTRIBUTES: {'2-s2.0-84949'}
EDGE: ('Name8', 'Name9') | COMMON ATTRIBUTES: {'2-s2.0-84940'}
EDGE: ('Name1', 'Name9') | COMMON ATTRIBUTES: {'2-s2.0-84905'}
마지막으로 참고 : 두 노드 사이에 여러 가장자리가해야하는 경우 MultiGraph
을 사용합니다.
NetworkX에는 기본 제공 방법이 없다고 생각합니다.하지만 모든 노드를 만든 다음 "특성"을 반복하고 적절한 가장자리를 추가하여 확실히 수행 할 수 있습니다. – BrenBarn