User_ID | Friend_Id | IsFriend |
---|---|---|
1 | 2 | 1 |
2 | 3 | 1 |
3 | 4 | 0 |
nodes = (user_id, friend_id) Connect nodes through egde = If: IsFriend = 1
User_ID | Friend_Id | IsFriend |
---|---|---|
1 | 2 | 1 |
2 | 3 | 1 |
3 | 4 | 0 |
nodes = (user_id, friend_id) Connect nodes through egde = If: IsFriend = 1
If you want edges to be present only if IsFriend == 1
then:
import pandas as pd
import networkx as nx
import numpy as np
df = pd.DataFrame.from_dict({'UserID': [1, 2, 3],
'Friend_Id': [2, 3, 4],
'IsFriend': [1, 1, 0]})
G = nx.Graph()
G.add_nodes_from(pd.concat([df.UserID, df.Friend_Id], axis=0))
G.add_edges_from(np.array(df[df.IsFriend.eq(1)][['UserID', 'Friend_Id']]))
If you're okay with IsFriend == 0
implying an edge but with zero weight, then you can simply do:
H = nx.from_pandas_edgelist(df,
source='UserID',
target='Friend_Id',
create_using=nx.Graph,
edge_attr='IsFriend')