Python 从数据框中,在不同行之间构建networkx图表或流程图,在某些列中使用公共值
我正在处理显示跨多行订单流的数据,每行都是一个独立的站点。示例数据如下所示:Python 从数据框中,在不同行之间构建networkx图表或流程图,在某些列中使用公共值,python,pandas,networkx,flowchart,Python,Pandas,Networkx,Flowchart,我正在处理显示跨多行订单流的数据,每行都是一个独立的站点。示例数据如下所示: Firm event_type id previous_id 0 A send 111 1 B receive and send 222 111 2 C receive and execute 333 222 3 D receive and execute 44
Firm event_type id previous_id
0 A send 111
1 B receive and send 222 111
2 C receive and execute 333 222
3 D receive and execute 444 222
4 E receive and cancel 123 100
此处的链接由两个字段“id”和“previous_id”决定。例如,在样本数据中,企业B的previous_id
与企业A的id
相同,111。因此,订单从公司A流向公司B
对于企业E,由于其先前的\u id
与任何行的id
不匹配,我打算将其作为流程中的一个独立部分
因此,我希望在样本数据的基础上实现以下目标:
(颜色仅用于说明,不是必须的颜色)
我一直在努力寻找@Dinari在这方面的答案,但没有成功。我希望networkx定向图表的标签是一列,而不是具有共享值的列
谢谢
# convert dataypes to ensure that dictionary access will work
df['id'] = df['id'].astype(str)
df['previous_id'] = df['previous_id'].astype(str)
# create a mapping from ids to Firms
replace_dict = dict(df[['id', 'Firm']].values)
# apply that mapping. If no Firm can be found use placeholders 'no_source' and 'no_target'
df['source'] = df['previous_id'].apply(lambda x: replace_dict.get(x) if replace_dict.get(x) else 'no_source' )
df['target'] = df['id'].apply(lambda x: replace_dict.get(x) if replace_dict.get(x) else 'no_target' )
#make the graph
G = nx.from_pandas_edgelist(df, source='source', target='target')
# drop all placeholder nodes
G.remove_nodes_from(['no_source', 'no_target'])
# draw graph
nx.draw_networkx(G, node_shape='s')
编辑:要包括箭头,请创建有向图(有向图):
非常感谢你的回答。还有一件事:
draw\u networkx
函数不显示节点之间的方向,这对我的情况非常重要。是否需要修改代码来实现这一点?谢谢
#make the graph
G = nx.from_pandas_edgelist(df, source='source', target='target', create_using=nx.DiGraph)