【问题标题】:From a Pandas Dataframe, build networkx chart or flow chart between different rows with common values in certain columns从 Pandas 数据框中,在某些列中具有共同值的不同行之间构建 networkx 图表或流程图
【发布时间】:2021-04-28 22:45:55
【问题描述】:

我正在处理显示多行订单流的数据,每一行都是一个独立的停靠点/站点。示例数据如下所示:

  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,由于其 previous_id 与任何行的 id 都不匹配,我打算将其作为流程中的一个独立部分。

因此,我想根据样本数据实现的目标是这样的:

(颜色仅用于说明目的,不是必须的)。

我一直在努力解决@Dinari 在这个related question 中的回答,但无法让它发挥作用。我希望 networkx 有向图的标签是除具有共享值的列之外的列。

谢谢。

【问题讨论】:

    标签: python pandas networkx flowchart


    【解决方案1】:
    # 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')
    

    编辑:要包含箭头,创建有向图 (DiGraph):

    #make the graph
    G = nx.from_pandas_edgelist(df, source='source', target='target', create_using=nx.DiGraph)
    

    【讨论】:

    • 非常感谢您的回答。还有一件事:draw_networkx 函数不显示节点之间的方向,这对我来说非常重要。反正有没有修改你的代码来实现这一点?谢谢。
    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多