Here is the script:
import pandas as pd
import networkx as nx
data = {
"Product": ["A", "B", "C", "D", "E"],
"Selling_Locations": [[1, 2, 3], [2, 5], [7, 8, 9, 10], [5, 4], [10, 11]]
}
df = pd.DataFrame(data)
G = nx.Graph()
for product in df["Product"]:
G.add_node(product)
for i in range(len(df)):
for j in range(i + 1, len(df)):
if set(df["Selling_Locations"][i]) & set(df["Selling_Locations"][j]):
G.add_edge(df["Product"][i], df["Product"][j])
groups = list(nx.connected_components(G))
for i, group in enumerate(groups, 1):
print(f"Group {i}: {sorted(group)}")
Ouput: