使用分组列的邻接矩阵

Adjacency matrix using grouping column

我目前正开始接触 pandas 我想知道是否有一个函数可以为我提供 DataFrame 中项目的常见类别。可视化:

这些是我的数据(显然是高度简化的例子)

   Discipline   Person
0    football   Alanis
1    football  Bernard
2    football  Delilah
3  basketball  Charlie
4  basketball  Delilah
5      tennis  Charlie

而且我想找出哪两个人共享一个学科,最好是像这样的矩阵形式:

        Alanis  Bernard Charlie Delilah
Alanis  True    True    False   True    
Bernard True    True    False   True
Charlie False   False   True    True
Delilah True    True    True    True    

或者,它可以是一个返回常见类别列表的函数。
我什至不知道 pandas 是否是完成此类任务的最佳工具(可能不是),正如我所说,我仍然是个菜鸟。不过,我非常感谢你的帮助。 谢谢!

value_counts() 函数查找给定 Series 对象中每个元素的唯一值计数。输出:现在我们将使用系列。 value_counts() 函数查找给定 Series 对象中每个唯一值的值计数。

一种方法是构建一个网络,并从中获取 adjacency matrix:

import networkx as nx
from itertools import combinations, chain

L = df.groupby('Discipline').Person.agg(list)

G = nx.Graph()
L = [list(combinations(i,2)) for i in L.values.tolist()]
G.add_edges_from(chain.from_iterable(L))

nx.to_pandas_adjacency(G, nodelist=sorted(G.nodes())).astype(bool)

          Alanis  Bernard  Charlie  Delilah
Alanis    False     True    False     True
Bernard    True    False    False     True
Charlie   False    False    False     True
Delilah    True     True     True    False

如果要将对角线值设置为 True,只需添加:

import numpy as np
out[:] = out.values + np.eye(out.shape[1], dtype=bool)

print(out)

         Alanis  Bernard  Charlie  Delilah
Alanis     True     True    False     True
Bernard    True     True    False     True
Charlie   False    False     True     True
Delilah    True     True     True     True