sam47
sam47

Reputation: 11

DataFrame index and column as nodes for Networkx

I'm looking to convert a DataFrame to a NetworkX graph: I would like to use the Dataframe as a map where the indexes are the "sources" and the columns are the "targets". The values should be the weights.

df = pd.DataFrame(np.random.randint(0,3,size=(4, 4)), columns=list('ABCD'), index = list('ABCD'))
df

G = nx.from_pandas_edgelist(
    df, source=df.index, target=df.column, create_using=nx.DiGraph
)

Here is a example of DataFrame, each index should connect to a column if the value is non-zero.

Would you know how to?

Upvotes: 0

Views: 333

Answers (1)

AveragePythonEnjoyer
AveragePythonEnjoyer

Reputation: 1165

Use nx.from_pandas_adjacency():

import pandas as pd
import numpy as np
import networkx as nx

df = pd.DataFrame(np.random.randint(0,3,size=(4, 4)), columns=list('ABCD'), index = list('ABCD'))

G = nx.from_pandas_adjacency(df, create_using=nx.DiGraph)

As the comment form @Huug points out be aware of passing create_using=nx.DiGraph to the command, to ensure it is created as a directed graph.

Upvotes: 1

Related Questions