Data & ML & AI/NetworkX

[NetworkX] 그래프 데이터 읽기 (파이썬 네트워크 분석 6)

뇌님 2022. 10. 11. 20:05
반응형

네트워크 그래프를 생성하더라도 데이터를 읽어내지 못한다면 쓸모가 없습니다.

이번엔 구축된 그래프에서 데이터를 읽어보겠습니다.

 

아래의 그래프를 기준으로 진행하겠습니다.

오른쪽의 그래프를 아래의 코드로 구축합니다.

import networkx as nx

G = nx.Graph()

# 엣지 하나씩 정의하기
G.add_edge('A','B', weight=6, relation='family')
G.add_edge('E','J', weight=15, relation='family')

# 한번에 여러 엣지 정의하기
friend = [('B','C',13),('G','F',9)]
coworker = [('C','F',21),('D','E',2),('E','I',10),('I','J',3),('E','H',9)]
neighbor = [('C','E',25)]
G.add_weighted_edges_from(friend, relation='friend')
G.add_weighted_edges_from(coworker, relation='coworker')
G.add_weighted_edges_from(neighbor, relation='neighbor')

여기서는 무방향 그래프(nx.Graph())만을 예시로 하였지만,

방향 그래프(nx.DiGraph())에서도 동일하게 적용할 수 있습니다.

 

1. 모든 엣지 리스트 확인하기

# 모든 엣지의 리스트 확인하기
G.edges()
# 출력결과
EdgeView([('A', 'B'), ('B', 'C'), ('E', 'J'), ('E', 'D'), ('E', 'I'),
                   ('E', 'H'), ('E', 'C'), ('J', 'I'), ('C', 'F'), ('G', 'F')])

 

2. 엣지가 가진 모든 속성까지 확인하기

# 모든 엣지가 가진 속성도 함께 확인하기
G.edges(data=True)
# 출력결과
EdgeDataView([('A', 'B', {'weight': 6, 'relation': 'family'}), ('B', 'C', {'relation': 'friend', 'weight': 13}), ('E', 'J', {'weight': 15, 'relation': 'family'}), 
              ('E', 'D', {'relation': 'coworker', 'weight': 2}), ('E', 'I', {'relation': 'coworker', 'weight': 10}), ('E', 'H', {'relation': 'coworker', 'weight': 9}), 
              ('E', 'C', {'relation': 'neighbor', 'weight': 25}), ('J', 'I', {'relation': 'coworker', 'weight': 3}), ('C', 'F', {'relation': 'coworker', 'weight': 21}), 
              ('G', 'F', {'relation': 'friend', 'weight': 9})])

 

3. 엣지가 가진 특정 속성만 확인하기

# 모든 엣지의 특정 속성만 확인하기
G.edges(data='relation')
# 출력결과
EdgeDataView([('A', 'B', 'family'), ('B', 'C', 'friend'), ('E', 'J', 'family'), ('E', 'D', 'coworker'), 
              ('E', 'I', 'coworker'), ('E', 'H', 'coworker'), ('E', 'C', 'neighbor'), ('J', 'I', 'coworker'), 
              ('C', 'F', 'coworker'), ('G', 'F', 'friend')])

 

4. 특정 엣지의 속성 확인하기

# 방법1
G['A']['B']

# 방법2
G.edges['A','B']

# 방법3
G['A']['B']['relation']
# 방법1,2 출력결과
{'weight': 6, 'relation': 'family'}

# 방법3 출력결과
'family'

 

여기서 유의 사항이 있습니다.

NetwrokX 버전이 1.X인 경우와 2.X인 경우 좀 다를 수 있습니다.

자습에 도움을 얻고있는 Coursera강의에서는 G.edge['A']['B']를 사용하고 있습니다. (위의 사진)

버전 1.X 기준인 것으로 보입니다.

 

하지만 버전 2.X에서는 Graph 객체가 edge attribute를 가지지 않습니다.

버전 2.X에서 사용하면 AttributeError가 나타납니다.

print(nx.__version__)
G.edge['A']['B']

# 출력결과
2.6.3
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-40-23c5e6755858> in <module>
      1 print(nx.__version__)
----> 2 G.edge['A']['B']

AttributeError: 'Graph' object has no attribute 'edge'

 

NetwrokX 2.X.X를 사용하신다면 G['A']['B'], G.edges['A','B'] 와 같은 방법을 사용하셔야 합니다.

참조 : https://networkx.org/documentation/stable/tutorial.html#accessing-edges-and-neighbors

 

Tutorial — NetworkX 2.8.7 documentation

Tutorial This guide can help you start working with NetworkX. Creating a graph Create an empty graph with no nodes and no edges. >>> import networkx as nx >>> G = nx.Graph() By definition, a Graph is a collection of nodes (vertices) along with identified p

networkx.org

 

반응형