How to link two columns based on a third columns to build network

Viewed 350

I am new in networkx and python. I have a database has 3 columns like this:

f_id s_id date
12345 506678 24-05-2005

i want to create a network by networkx but first i need to connect the nodes based on the date

for example: lf_id -> s_id

where (->) the link is the date

I know how to create the network as a directed network but i have tried to connect the two columns and i couldn't do that so what i did is something like this:

import netowkrx as nx
import pandas as pd

df = pd.read_csv("connect_data.csv")

df1 = df[['f_id', 's_id', 'date']]

G = nx.DiGraph()
G = nx.from_pandas_dataframe(df,['f_id','s_id'])

but that not make it right! and i couldn't figure out a way can anyone help please on how to connect the two columns based on the dates.

1 Answers

You can use nx.from_pandas_edgelist, which allows to create a graph from a dataframe with the edge data. Since it appears that you want the date to be picked up by the graph, you can also add edge attributes. The resulting edges would look as follows:

G = nx.from_pandas_edgelist(df, source='f_id', target='s_id', edge_attr='date')

G.edges(data=True)
# EdgeDataView([(12345, 506678, {'date': '24-05-2005'})])
Related