用 pandas 表示网络数据

Python 网络分析中级

Eric Ma

Data Carpentry instructor and author of nxviz package

用于存储网络数据的 CSV 文件

  • CSV 文件
person,party,weight
Barrett.Samuel,LondonEnemies,1
Barrett.Samuel,StAndrewsLodge,1
Marshall.Thomas,LondonEnemies,1
Eaton.Joseph,TeaParty,1
Bass.Henry,LondonEnemies,1
Python 网络分析中级

用于存储网络数据的 CSV 文件

  • 优点:
    • 可读性强
    • 可用 pandas 进一步分析
  • 缺点:
    • 重复;占用磁盘空间
  • 两个 DataFrame:节点表与边表
Python 网络分析中级

节点表与边表

  • 节点表
    • 每行一个节点
    • 列为该节点的元数据
  • 边表
    • 每行一条边
    • 列为该边的元数据
Python 网络分析中级

Pandas 与图

list(G.nodes(data=True))
[(0, {'bipartite': 0}),
(1, {'bipartite': 0}),
(2, {'bipartite': 0}),
...]
nodelist = []

for n, d in G.nodes(data=True): node_data = dict() node_data['node'] = n
node_data.update(d)
nodelist.append(node_data)
Python 网络分析中级

Pandas 与图

nodelist
[{'bipartite': 0, 'node': 0},
{'bipartite': 0, 'node': 1},
{'bipartite': 0, 'node': 2},
{'bipartite': 0, 'node': 3},
{'bipartite': 0, 'node': 4},...]
Python 网络分析中级

Pandas 与图

import pandas as pd
pd.DataFrame(nodelist)
  bipartite  node
0           0     0
1           0     1
2           0     2
3           0     3
4           0     4
5           1     5
6           1     6
7           1     7
pd.DataFrame(nodelist).to_csv('my_file.csv')
Python 网络分析中级

Passons à la pratique !

Python 网络分析中级

Preparing Video For Download...