在python中创建非定向邻接矩阵

时间:2018-02-19 07:55:44

标签: python

我有一个邻接列表,我想将其转换为矩阵,我的数据看起来像这样

User_Name    M_User     Total
user 1       user 2      1
user 1       user 3      1
user 1       user 3      1
user 1       user 7      1
user 3       user 2      1
user 2       user 7      1

最终结果应如下所示

            user 1   user 2   user 3   user 7 

user 1         0         1        1       1
user 2         1         0        1       1
user 3         1         1        0       0
user 7         1         1        0       0

一个无方向矩阵,但我得到一个方向矩阵

            user 1   user 2  user 3  user 7 
user 1         0       1       1        1
user 2         0       0       0        1
user 3         0       1       0        0
user 7         0       0       0        0

如何获得无向矩阵,这是我的代码

import pandas as pd
df = pd.read_csv("C:/Users/file.csv")
df = df.drop_duplicates()

df = pd.crosstab(df.User_Name, df.M_User)
idx = df.columns.union(df.index)
df = df.reindex(index = idx, columns=idx, fill_value=0)

1 个答案:

答案 0 :(得分:1)

只要矩阵是正方形,只需取原始矩阵及其转置副本的并集:

df.T|df
#        user 1  user 2  user 3  user 7
#user 1       0       1       1       1
#user 2       1       0       1       1
#user 3       1       1       0       0
#user 7       1       1       0       0