如何从节点 = (user_id, friend_id) 和边缘 = (IsFriend, 值为 0/1) 的数据框列创建图表
How can I create a graph from dataframe columns where nodes = (user_id, friend_id) and edge = (IsFriend, value is 0/1)
User_ID
Friend_Id
IsFriend
1
2
1
2
3
1
3
4
0
节点数 = (user_id, friend_id)
通过egde连接节点= If: IsFriend = 1
如果您希望边仅在 IsFriend == 1
时出现,则:
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']]))
如果您同意 IsFriend == 0
暗示边缘但权重为零,那么您可以简单地执行:
H = nx.from_pandas_edgelist(df,
source='UserID',
target='Friend_Id',
create_using=nx.Graph,
edge_attr='IsFriend')
User_ID | Friend_Id | IsFriend |
---|---|---|
1 | 2 | 1 |
2 | 3 | 1 |
3 | 4 | 0 |
节点数 = (user_id, friend_id) 通过egde连接节点= If: IsFriend = 1
如果您希望边仅在 IsFriend == 1
时出现,则:
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']]))
如果您同意 IsFriend == 0
暗示边缘但权重为零,那么您可以简单地执行:
H = nx.from_pandas_edgelist(df,
source='UserID',
target='Friend_Id',
create_using=nx.Graph,
edge_attr='IsFriend')