擅长:python、mysql、java
<p>我们可以使用Networkx库:</p>
<pre><code>import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
# Read in pandas dataframe using copy and paste
df = pd.read_clipboard()
# Create graph network from pandas dataframe
G = nx.from_pandas_edgelist(df, 'Col1', 'Col2')
# Create id, Series
id = pd.Series(['A', 'F'])
# Move values in the index of the Series
id.index=id
# Use `single_source_shortest_path` method in nx for each value in, id, Series
id.apply(lambda x: list(nx.single_source_shortest_path(G, x, 3).keys())[1:])
</code></pre>
<p>输出:</p>
<pre><code>A [B, C, D, G]
F [E]
dtype: object
</code></pre>
<p>打印图形表示:</p>
<p><a href="https://i.stack.imgur.com/vwn8n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vwn8n.png" alt="enter image description here"/></a></p>