微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将平行边与熊猫配对

如何解决将平行边与熊猫配对

问题

我需要在 Pandas 的边列表中查找并返回所有反向平行边。我的要求是我只使用 Pandas 或 Python 内置函数。该函数应返回具有反向平行边的所有行,以及它们的原始索引 ID,并有一个“pair_id”列指示哪些行是平行的。

我已经创建了一个执行此操作的函数,但我对 pair_id 阶段并不满意,因为它依赖于循环并且有效地执行了两次识别过程。有什么可以改进的建议吗?

功能

def find_parallel_edges(edge_list:pd.DataFrame)->pd.DataFrame:
    
    # setting the edge_list to be multi-indexed by source and target
    main = edge_list.copy()
    main['index'] = main.index
    main.set_index(['source','target'],drop=False,inplace=True)

    # creating a reversed version of the index
    rev_index = edge_list.set_index(['target','source']).index
   
    #identifying where the main index and its reversed version intersects 
    intersect_filter = main.index.intersection(rev_index)
    parallel_data = main.loc[intersect_filter]
    
    # Pair identification by iterating through all pairs and their reverse,#    locating those rows in the data and assigning them the same id.
    parallel_rev_index = list(map(lambda x: (x[1],x[0]),parallel_data.index))
    for i,(main,rev) in enumerate(zip(parallel_data.index,parallel_rev_index)):
        parallel_data.loc[[main,rev],'pair_id'] = i
    return parallel_data.set_index('index')

示例

toy_df

/ 来源 目标
0
1 玛丽 弗雷德
2 玛丽
3 弗雷德 玛丽
4
res = find_parallel_edges(toy_df)

res

/ 来源 目标 pair_id
0 3
1 玛丽 弗雷德 2
3 弗雷德 玛丽 2
4 3

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。