本文介绍了如何在Python中从邻接矩阵创建边缘列表数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个格式为 df 的pandas数据框(认为是否作为网络中节点的加权邻接矩阵),
I have a pandas dataframe (think of if as a weighted adjacency matrix of nodes in a network) of the 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
我想获取一个表示边缘列表的数据框。对于上面的示例,我需要某种形式, edge_list_df ,
I want to get a dataframe that instead represents an edge list. for the above example, I would need something of the form, edge_list_df,
Source Target Weight
0 A B 0.5
1 A C 0.5
2 A D 0
3 B A 1
4 B C 0
5 B D 0
6 C A 0.8
7 C B 0
8 C D 0.2
9 D A 0
10 D B 0
11 D C 1
最有效的方法是什么?
推荐答案
将对角线标记为 nan
,然后我们 stack
Mark diagonal as nan
, then we stack
df.values[[np.arange(len(df))]*2] = np.nan
df
Out[172]:
A B C D
A NaN 0.5 0.5 0.0
B 1.0 NaN 0.0 0.0
C 0.8 0.0 NaN 0.2
D 0.0 0.0 1.0 NaN
df.stack().reset_index()
Out[173]:
level_0 level_1 0
0 A B 0.5
1 A C 0.5
2 A D 0.0
3 B A 1.0
4 B C 0.0
5 B D 0.0
6 C A 0.8
7 C B 0.0
8 C D 0.2
9 D A 0.0
10 D B 0.0
11 D C 1.0
这篇关于如何在Python中从邻接矩阵创建边缘列表数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!