0
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

  • Hi Mayank, pardon me for dropping in like this. Just wanted to let you know it's not always necessary to delete a [post](https://stackoverflow.com/questions/70888737/cannot-implicitly-convert-type-void-to-list-of-class-type) that is closed. You can always make it better by following the instructions on the closure header. Doing so will allow others to vote for it to be _re-opened_. So it's not always the end of the world. Remember, we are all here to help each other. :) Have a great day! –  Jan 28 '22 at 04:53
  • Hello Micky, you have been very helpful. I tried for so long to modify the question and add more details but for some reason, I am not able to modify the code. – Mayank Semwal Jan 28 '22 at 05:07
  • Not to worry, you can always post a _new_ question with the changes that you wanted. :) –  Jan 28 '22 at 05:28
  • I tried but still I am not able to add the code. While posting it keep saying "Please add some context to explain the code sections (or check that you have not incorrectly formatted all of your question as code". – Mayank Semwal Jan 28 '22 at 05:31
  • Ah ok, in your post where you have the code listing, you need to add some sort of description about your problem, any error you might be getting, things you have tried, that sort of thing. [Here's an example](https://stackoverflow.com/q/70886713/585968) –  Jan 28 '22 at 06:05
  • 1
    Got it. Thanks a lot, @MickyD. Appreciate your time and effort. – Mayank Semwal Jan 28 '22 at 06:34

1 Answers1

0

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')
Frodnar
  • 2,129
  • 2
  • 6
  • 20