添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

You can define your edges by defining all pairs of nodes that have to same value for 'X' and the same value for 'Y' using itertools.combinations .

import itertools.combinations as comb
edges = set()
for col in df:
    for _, data in df.groupby(col):
        edges.update(comb(data.index, 2))
G = nx.Graph()
G.add_nodes_from(df.index)
G.add_edges_from(edges)

IIUC:

Your indexes are the labels for your nodes. So, we need to to reshape dataframe a bit to create an edge list dataframe:

d1 = df.reset_index().set_index(['X',df.groupby('X').cumcount()]).unstack()['index']
d2 = df.reset_index().set_index(['Y',df.groupby('Y').cumcount()]).unstack()['index']
d3 = pd.concat([d1,d2]).set_axis(['source','target'], inplace=False, axis=1).dropna().astype(int)
G = nx.from_pandas_edgelist(d3, source='source', target='target')
nx.draw_networkx(G)

Output:

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.