繁体   English   中英

将邻接矩阵作为图 object 存储在 Python 中

[英]Storing adjacency matrix as graph object in Python

我有具有邻接方阵的网络数据,并且没有包含键(没有包含人员的标识符)。

如何使用 networkx package 将我的邻接矩阵(csv 文件)存储为图形 object?

要将矩阵存储为 csv 格式,我认为您应该首先将其转换为pandas DataFrame。 为此,您可以参考此https://networkx.org/documentation/stable//reference/generated/networkx.convert_matrix.to_pandas_adjacency.html.networkx.convert_matrix.to_pandas_adjacency 请注意,如果您想以 DataFrame 的格式为每个节点命名,您可能需要使用indexcolumns属性来自定义索引。

将图形转换为pandas DataFrame 后,可以使用to_csv导出。

There are several ways to get your adjacency matrix from csv format into a graph object, but the most straightforward, in my opinion, is to load the adjacency matrix using pandas, and then directly create a graph from the pandas dataframe object:

# Example 3x3 adjacency matrix in csv file:

# 0  1  0
# 1  0  1
# 0  1  0

import networkx as nx
import pandas as pd

adjmat_df = pd.read_csv('adjmat.csv',header=None)

# This gives us the following dataframe:
#    0  1  2
# 0  0  1  0
# 1  1  0  1
# 2  0  1  0

# Create networkx graph object
G = nx.from_pandas_adjacency(adjmat_df)

print(nx.info(G))
# Name: 
# Type: Graph
# Number of nodes: 3
# Number of edges: 2
# Average degree:   1.3333

nx.draw_shell(G, with_labels=True, alpha=0.7, font_size=15, node_size=500, node_color='r')

图形

如果您有要使用的节点标签,您只需将 pandas dataframe 的列和索引设置为节点标签列表:

node_labels = ['A','B','C']
adjmat_df.columns = node_labels
adjmat_df.index = node_labels

G = nx.from_pandas_adjacency(adjmat_df)
nx.draw_shell(G, with_labels=True, alpha=0.7, font_size=15, node_size=500, node_color='r')

graph_with_node_labels (

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM