我正在尝试向二部NetworkX图中的一系列节点添加属性。一组节点是员工姓名;另一组是电影名称。它们看起来像这样:
# This is the set of employees
employees = set(['Pablo',
'Lee',
'Georgia',
'Vincent',
'Andy',
'Frida',
'Joan',
'Claude'])
# This is the set of movies
movies = set(['The Shawshank Redemption',
'Forrest Gump',
'The Matrix',
'Anaconda',
'The Social Network',
'The Godfather',
'Monty Python and the Holy Grail',
'Snakes on a Plane',
'Kung Fu Panda',
'The Dark Knight',
'Mean Girls'])我有一个Pandas数据帧中的网络数据:
df = df = pd.read_csv('Employee_Movie_Choices.txt', sep='\t')
#Employee Movie
0 Andy Anaconda
1 Andy Mean Girls
2 Andy The Matrix
3 Claude Anaconda
4 Claude Monty Python and the Holy Grail从中我创建了一个NetworkX图:
B = nx.from_pandas_dataframe(df, '#Employee', 'Movie')然后,我尝试使用以下循环将以下属性添加到节点:
for e in employees:
nx.set_node_attributes(B, {e: {'type'='employee'}})
for m in movies:
nx.set_node_attributes(B, {m: {'type'='movie'}})但会得到以下错误:
TypeError: set_node_attributes() missing 1 required positional argument: 'values'我不能解决这个问题。我也试过这个:
for e in emplyoees:
nx.set_node_attributes(B, name='type', values='employee')
for m in movies:
nx.set_node_attributes(B, name='type', values='movie')但每个for循环都会将其值分配给每个节点,即“employee”或“movie”。因此,电影将被标记为employee和employees,而employees将被标记为movies和movies。
这方面的任何帮助都是非常感谢的!
发布于 2019-06-23 20:32:00
看一下函数nx.set_node_attributes的the documentation。
该函数接受一个字典,其中键是节点,值是属性(在您的示例中是employee或movie )。它不能用于逐个更新节点。这里有一个解决方法,我们首先创建一个字典节点,然后在一个步骤中设置node:node_type属性:
node_attribute_dict = {}
for employee in employees:
node_attribute_dict[employee]='employee'
for movie in movies:
node_attribute_dict[movie]='movie'
nx.set_node_attributes(B,values = node_attribute_dict,name='node_type')https://stackoverflow.com/questions/56708529
复制相似问题