为pandas数据框中的两列创建邻接矩阵 [英] Create adjacency matrix for two columns in pandas dataframe

查看:337
本文介绍了为pandas数据框中的两列创建邻接矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其格式为:

I have a dataframe of the form:

index  Name_A  Name_B
  0    Adam    Ben
  1    Chris   David
  2    Adam    Chris
  3    Ben     Chris

我想获得Name_AName_B的邻接矩阵,即:

And I'd like to obtain the adjacency matrix for Name_A and Name_B, ie:

      Adam Ben Chris David
Adam   0    1    1     0
Ben    0    0    1     0
Chris  0    0    0     1
David  0    0    0     0

解决这个问题的最pythonic/可扩展的方法是什么?

What is the most pythonic/scaleable way of tackling this?

另外,我知道,如果行Adam, Ben在数据集中,那么在其他时候,Ben, Adam也将在数据集中.

Also, I know that if the row Adam, Ben is in the dataset, then at some other point, Ben, Adam will also be in the dataset.

推荐答案

您可以使用 crosstab ,然后 reindex 通过 union 的列和索引值:

You can use crosstab and then reindex by union of column and index values:

df = pd.crosstab(df.Name_A, df.Name_B)
print (df)
Name_B  Ben  Chris  David
Name_A                   
Adam      1      1      0
Ben       0      1      0
Chris     0      0      1

df = pd.crosstab(df.Name_A, df.Name_B)
idx = df.columns.union(df.index)
df = df.reindex(index = idx, columns=idx, fill_value=0)
print (df)
       Adam  Ben  Chris  David
Adam      0    1      1      0
Ben       0    0      1      0
Chris     0    0      0      1
David     0    0      0      0

这篇关于为pandas数据框中的两列创建邻接矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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