How to merge duplicate nodes in networkX without loosing edges

Viewed 205

I'm very new to python so forgive me this imporvised explanation here.

I'm building a network graph from Twiter data based on retweets, using the code provided here: https://github.com/ugis22/analysing_twitter/blob/master/Jupyter%20Notebook%20files/Interaction%20Network.ipynb

I have a dataframe with columns = ["created_at", "id","text", "user_id", "screen_name", "retweeted_id", "retweeted_screen_name", "followers_count"]

def get_interactions(row):
    # From every row of the original dataframe
    # First we obtain the 'user_id' and 'screen_name'
    user = row["user_id"], row["screen_name"]
    # Be careful if there is no user id
    if user[0] is None:
        return (None, None), []
    
    # The interactions are going to be a set of tuples
    interactions = set()
   
    #Add the interactions with retweets
    interactions.add((row["retweeted_id"], row["retweeted_screen_name"]))
    
    # Discard if user id is in interactions
    interactions.discard((row["user_id"], row["screen_name"]))
    # Discard all not existing values
    interactions.discard((None, None))
    # Return user and interactions
    return user, interactions

graph = nx.Graph()

for index, tweet in tweets_final.iterrows():
    user, interactions = get_interactions(tweet)
    user_id, user_name = user
    tweet_id = tweet["id"]
    for interaction in interactions:
        int_id, int_name = interaction
        
        graph.add_edge(user_id, int_id, tweet_id=tweet_id)
        
        graph.nodes[user_id]["name"] = user_name
        graph.nodes[int_id]["name"] = int_name

However, when I look at the list of nodes created, there are many duplicates. How could i merge these duplicates into single nodes without loosing the edges they both have?

I was trying to use this but it doesnt seem to work:

for interaction in interactions:  
    int_id, int_name = interaction 
    if user_id == int_id:
        nx.contracted_nodes(graph, user_id, int_id, self_loops=False)

Thank you in advance!

0 Answers
Related