python - 从数组及其转置创建邻接矩阵

标签 python pandas numpy adjacency-matrix

我有一个像这样的 pandas DataFrame:
enter image description here

我想创建一个这样的对称矩阵:
enter image description here

其中的值实际上是两个列表的交集长度。因此我做了这个功能:

 def intersectSize(l1, l2):
     return len(set(l1) & set(l2))

有没有类似这个的函数:

def createSymMatrix(array, func):
    ...
    return matrix

array 是我的初始数据框,funcintersectSize 函数?

编辑:用这两个衬垫弄明白了:

array = [[len(set(l1)&set(l2)) for l1 in df]] for l2 in df]
adj = pd.DataFrame(data=array, index=df.index, columns=df.index)

最佳答案

我想你需要这个,

r=[]
for val in list(itertools.product(df[0].values,df[0].values)):
    r.append( len(set(val[0])&set(val[1])) )
print pd.DataFrame(np.array(r).reshape(len(df),-1))

使用列表理解:

t= [len(set(val[0])&set(val[1])) for val in list(itertools.product(df[0].values,df[0].values))]
print pd.DataFrame(np.array(t).reshape(len(df),-1))

输出:

   0  1  2  3
0  3  0  0  1
1  0  1  0  1
2  0  0  2  0
3  1  1  0  2

关于python - 从数组及其转置创建邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53498901/

相关文章:

python - 如何使用 PyGithub 创建新的存储库

python - 按连续索引号分组

python - 将 numpy 多项式拟合到噪声数据

python - 如何使用 numpy 创建对角矩阵?

Python:如何读取具有不同分隔符的csv文件?

python - Pandas.to_datetime() 仅在数据框中的列上失败

python - 使用字典理解修改字典而不创建新字典

python - 如何查找 pyspark 数据帧内存使用情况?

python - wxPython wx.lib.plot.PlotCanvas 错误

python - ValueError : 2 columns passed, 传递的数据有 1 列