How to Create a Bipartite Graph From a Dataframe in Python
A bipartite graph is a type of graph in which the nodes can be divided into two disjoint sets, such that every edge connects a node from one set to a node from the other set.
To create a bipartite graph from a Python DataFrame you can use Pandas and NetworkX libraries.
The following example shows how to create a bipartite graph from a dataframe in Python.
Using NetworkX Library
We can use the NetworkX library to create a bipartite graph.
Suppose we have the following dataframe:
import pandas as pd
import networkx as nx
# Create dataframe
office_stuff = pd.DataFrame({
'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
'Price': [4500, 550, 250, 50, 350, 50],
'Status': [1, 1, 1, 0, 1, 1]
})
# Create sets
products = set(office_stuff["Product_Code"])
dates = set(office_stuff["Date"])
# Create an empty bipartite graph
G = nx.Graph()
# Add nodes
G.add_nodes_from(products, bipartite=0)
G.add_nodes_from(dates, bipartite=1)
# Add edges
for index, row in office_stuff.iterrows():
G.add_edge(row["Product_Code"], row["Date"])
# Plot bipartite graph
pos = nx.bipartite_layout(G, products)
nx.draw_networkx(G, pos=pos)
Output:
In this example, we use the NetworkX library to create a bipartite graph from the dataframe office_stuff.
The output shows the bipartite graph created from the dataframe.
Conclusion
We can use the NetworkX library to create a bipartite graph from a dataframe in Python.