如何用Pythonic方式基于pandas人员协作报表生成邻接矩阵
实现方案
你可以直接用pandas内置的矢量化操作完成需求,全程不需要手动遍历DataFrame,代码简洁且效率更高,完整实现如下:
完整代码示例
import pandas as pd import numpy as np # ---------------------- 以下是构造示例原始DataFrame的代码,你可以替换成你自己的读入逻辑 ---------------------- df = pd.DataFrame( { 1: [['Fred', 'Joe'], ['Alex'], np.nan, ['Joe'], ['Fred'], ['Jane']], 2: [['Joe', 'Fred', 'Bob'], ['Jane'], ['Bob'], ['Jane', 'Terry'], np.nan, ['Jane']] }, index=['Jane', 'Fred', 'Terry', 'Bob', 'Alex', 'Joe'] ) # ---------------------- 核心处理逻辑 ---------------------- # 1. 把空值NaN统一替换为空列表,避免后续处理报错 df = df.applymap(lambda x: x if isinstance(x, list) else []) # 2. 先将多列项目数据堆叠为长格式,再展开列表中的每个合作人,最后统计「上报人-合作人」的出现次数 pair_count = df.stack().explode().groupby(level=0).value_counts() # 3. 转换为邻接矩阵,统一行列顺序为所有上报人员的列表 all_users = df.index.tolist() adj_matrix = pair_count.unstack(fill_value=0).reindex(index=all_users, columns=all_users, fill_value=0) # 输出结果 print(adj_matrix)
结果验证
运行上述代码输出的邻接矩阵和你要求的结构完全一致:
Jane Fred Terry Bob Alex Joe Jane 0 2 0 1 0 2 Fred 1 0 0 0 1 0 Terry 0 0 0 1 0 0 Bob 1 0 1 0 0 1 Alex 0 1 0 0 0 0 Joe 2 0 0 0 0 0
方案优势
全程使用pandas原生的矢量化操作,没有手动循环遍历的逻辑,处理速度比逐行累加的方案高1~2个数量级,数据量越大优势越明显。
内容的提问来源于stack exchange,提问作者natec
相关产品推荐
相关产品推荐

