Search code examples
python-3.xattributesnodesnetworkx

TypeError when assigning node attributes in NetworkX


I am trying to add attributes to a series of nodes in a bipartite NetworkX graph. One set of nodes are employee names; the other set are movie names. They look like such:

# 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'])

I have the network data in a Pandas dataframe:

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

From which I create a NetworkX graph:

B = nx.from_pandas_dataframe(df, '#Employee', 'Movie')

Then, I try to add the following attributes to the nodes with the following loop:

for e in employees:
    nx.set_node_attributes(B, {e: {'type'='employee'}})

for m in movies:
    nx.set_node_attributes(B, {m: {'type'='movie'}})

But get the following error:

TypeError: set_node_attributes() missing 1 required positional argument: 'values'

I cannot resolve this issue. I tried this as well:

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')

But each for loop assigns its value, i.e. 'employee' or 'movie' to every single node. So movies will be labeled employee along with employees, and employees will be labeled movie along with movies.

Any help with this is greatly appreciated!


Solution

  • Have a look at the documentation for the function nx.set_node_attributes.

    The function takes a dictionary in which keys are nodes and values are the attributes (employee or movie in your example). It cannot be used to update the nodes one by one. Here is one workaround, where we first create a dictionary node:node_type, then in one step set the node attribute:

    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')