[Python] How to assign subgraph IDs based on weakly connected user pairs, but split when no...

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working with a dataset where I want to assign a sub_graph ID to user interactions. Each row in the data represents a directed edge between an actor_user_id and a related_user_id.

    I want to compute a sub_graph ID such that:

    Rows belong to the same sub_graph if they are connected (even indirectly) through shared users.

    However, if two edges only share the same actor_user_id, they should not be grouped unless their related_user_ids are also connected.

    Here’s a simplified example:

    import pandas as pd
    import networkx as nx
    import matplotlib.pyplot as plt

    # Dummy data
    edges = pd.DataFrame({
    'properties_id': ['A', 'A', 'A', 'A'],
    'global_journey_id': ['A1', 'A1', 'A1', 'A1'],
    'actor_user_id': ['abc', 'abc', 'pat', 'abc'],
    'related_user_id': ['def', 'efg', 'def', 'lal'],
    })


    actor_user_id related_user_id sub_graph
    abc def 1
    pat def 1
    abc efg 2
    abc lal 3


    I've tried using NetworkX like this:

    G = nx.DiGraph()
    G.add_edges_from(zip(edges['actor_user_id'], edges['related_user_id']))
    components = list(nx.weakly_connected_components(G))


    But this gives me only one connected component because abc is a common node across many edges.

    Question:

    How can I build logic that ensures subgraphs are only formed when there is a true "shared connection", not just a shared actor_user_id?

    Is there a way to force the graph to disconnect branches that don’t have overlapping related_user_ids?

    Any idea or trick to break down these graphs properly (even custom component grouping logic) would be super appreciated

    Continue reading...

Compartilhe esta Página