Python 将有向的流数据合并为无向的流
2020-09-17 本文已影响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')