美文网首页
Python 将有向的流数据合并为无向的流

Python 将有向的流数据合并为无向的流

作者: 王叽叽的小心情 | 来源:发表于2020-09-17 19:30 被阅读0次

    需求:有一份人口流动数据,是有向的人口流动,尝试合并为合并的流动,数值为双向流动之和。

    解决方法:一开始尝试采用merge的方法,最后总是差一点东西,最后得到间接的networkx中的有向图转无向图的方法,再对每个边进行计算,代码如下:

      # 读取流数据为dataframe,主要是source,target,value字段
        input_path = "D:\\wyx2020\\flow\\"
        df = pd.read_csv(input_path+"flow.csv", header=0, encoding='gbk')
        
        # 采用network中的有向图到无向图的转换
        # 构建有向图
        G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr=True, create_using=nx.DiGraph())
        undirected = G.to_undirected() #转变为无向图
        
    # 依然需要遍历每条边,进行属性计算
        for edge in undirected.edges(data=True):
            direction_1 = df.loc[(df['source'] == edge[0]) & (df['target'] == edge[1])]
            direction_2 = df.loc[(df['source'] == edge[1]) & (df['target'] == edge[0])]
            edges = pd.concat([direction_1, direction_2])
            edge[2]['bidirect'] = 1 if (not direction_1.empty) & (not direction_2.empty) else 0
            edge[2]['Value'] = edges['Value'].sum()
    
    # 将得到的dataframe输出
        nx.to_pandas_edgelist(undirected).to_csv(input_path+'undir_flow_del_inter_city.csv',
                                                 header=True, index=False, encoding='gbk')
    

    参考资料:https://stackoverflow.com/questions/52255502/how-to-transform-directed-graph-to-undirected-graph-while-recording-information

    相关文章

      网友评论

          本文标题:Python 将有向的流数据合并为无向的流

          本文链接:https://www.haomeiwen.com/subject/oglryktx.html