Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

networkx node attribute from a dataframe

import networkx as nx
import pandas as pd

# Build a sample dataframe (with 2 edges: 0 -> 1, 0 -> 2, node 0 has attr_1 value of 'a', node 1 has 'b', node 2 has 'c')
d = {'node_from': [0, 0], 'node_to': [1, 2], 'src_attr_1': ['a','a'], 'tgt_attr_1': ['b', 'c']}
df = pd.DataFrame(data=d)
G = nx.from_pandas_edgelist(df, 'node_from', 'node_to')

# Iterate over df rows and set the source and target nodes' attributes for each row:
for index, row in df.iterrows():
    G.nodes[row['node_from']]['attr_1'] = row['src_attr_1']
    G.nodes[row['node_to']]['attr_1'] = row['tgt_attr_1']

print(G.edges())
print(G.nodes(data=True))
Comment

PREVIOUS NEXT
Code Example
Python :: python use getcontext 
Python :: df iloc 
Python :: how to access a file from root folder in python project 
Python :: python add hyphen to string 
Python :: find the difference of strings in python 
Python :: how delete an entry tkinter 
Python :: select column in pandas dataframe 
Python :: Django - Knox auth setup 
Python :: golang get started 
Python :: python standard normal cumulative distribution 
Python :: get hours from datetime.timedelta in python (Django) 
Python :: aiohttp 
Python :: pandas change period 
Python :: python keyerror 
Python :: stemmer nltk 
Python :: clipboard python 
Python :: how to find a specific word in a list python 
Python :: python split range into n groups 
Python :: python vector class 
Python :: python cartesian coordinates code 
Python :: Python NumPy array_split Function Syntax 
Python :: remove punctuation 
Python :: how to create dictionary in python 
Python :: sorted string 
Python :: Python Renaming a Directory or a File 
Python :: how to add condition if null value in django orm 
Python :: subplots 
Python :: Reverse an string Using Loop in Python 
Python :: correlation with target variable python 
Python :: created by and updated by in django 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =