如何从 pandas 邻接矩阵数据帧创建有向networkx图? [英] How to create a directed networkx graph from a pandas adjacency matrix dataframe?

查看:176
本文介绍了如何从 pandas 邻接矩阵数据帧创建有向networkx图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下格式的熊猫数据框, df

I have a pandas dataframe of the the following form, df,

    A    B    C    D
A   0   0.5   0.5  0 
B   1    0    0    0
C   0.8  0    0   0.2
D   0    0    1    0

我正在尝试由此创建一个networkx图.我尝试了以下代码变体:

I am trying to create a networkx graph from this. I have tried the following variations of code:

A)

G=networkx.from_pandas_adjacency(df)
G=networkx.DiGraph(G) 

B)

G=networkx.from_pandas_adjacency(df, create_using=networkx.DiGraph())

但是,最终发生的事情是图形对象:

However, what ends up happening is that the graph object either:

(对于选项A)基本上只取任意两个给定节点之间两个平行边中的一个值,并删除另一个值.

(For option A) basically just takes one of the values among the two parallel edges between any two given nodes, and deletes the other one.

(对于选项B)采用任意两个给定节点之间的两个平行边中的一个值,作为两个边的值.

(For option B) takes one of the values among the two parallel edges between any two given nodes, as the value for both edges.

例如,

print( list ( filter ( lambda x: x[0]=='A' and x[1] == 'B', list(G.edges.data()) ) ) )

print( list ( filter ( lambda x: x[0]=='B' and x[1] == 'A', list(G.edges.data()) ) ) )

为选项A打印1和[]. 为选项B打印两个1.

prints 1 and [] for option A. prints two 1s for option B.

我该如何解决此问题?

推荐答案

尝试使用numpy作为解决方法.

Try using numpy as a workaround.

G = nx.from_numpy_matrix(df.values, parallel_edges=True, 
                         create_using=nx.MultiDiGraph())

# Because we use numpy, labels need to be reset
label_mapping = {0: "A", 1: "B", 2: "C", 3: "D"}
G = nx.relabel_nodes(G, label_mapping)

G.edges(data=True)

OutMultiEdgeDataView([('A', 'B', {'weight': 0.5}), 
                      ('A', 'C', {'weight': 0.5}), 
                      ('B', 'A', {'weight': 1.0}), 
                      ('C', 'A', {'weight': 0.8}), 
                      ('C', 'D', {'weight': 0.2}), 
                      ('D', 'C', {'weight': 1.0})])

在更一般的情况下,要获取label_mapping,您可以使用

In a more general case, to get label_mapping you can use

label_mapping = {idx: val for idx, val in enumerate(df.columns)}

这似乎是networkx 2.0中的错误.他们将在2.1中修复它.有关更多信息,请参见此问题.

This seems to be a bug in networkx 2.0. They will fix it in 2.1. See this issue for more information.

这篇关于如何从 pandas 邻接矩阵数据帧创建有向networkx图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆