Given a dataframe with one column of players and other column with a subset of teammates, form the entire teams
Create connected_components with explode column teammates
by DataFrame.explode
:
import networkx as nx
# Create the graph from the dataframe
g = nx.Graph()
g.add_edges_from(df[['player','teammates']].explode('teammates').itertuples(index=False))
new = list(nx.connected_components(g))
print (new)
[{'F', 'A', 'C'}, {'B'}, {'Q', 'K', 'H', 'J', 'D'}]
If need lists:
L = [list(x) for x in new]