私はこのようなDataFrameを持っています:
vals = {"operator": [1, 1, 1, 2, 3, 5], "nextval": [2, 3, 6, 4, 5, 6]}
df = pd.DataFrame(vals)
operator nextval
0 1 2
1 1 3
2 1 6
3 2 4
4 3 5
5 5 6
私がやろうとしていることは、厳密に最短のパスではなく、演算子とnextvalsを使用して、1のような開始点と6のような終了点から可能なすべてのパスのリストを取得することです。出力は柔軟にすることができますが、私はこのようなもの、またはこれを伝えるものを探しています:
1 -> 6
1 -> 2 -> 4
1 -> 3 -> 5 -> 6
私はそれに近づけることはできますが、dictは2つの同じキーを処理できないため、再帰を正しく行う方法がわかりません。
import pandas as pd
vals = {"operator": [1, 1, 1, 2, 3, 5], "nextval": [2, 3, 6, 4, 5, 6]}
df = pd.DataFrame(vals)
df1 = df.set_index("operator")
dictvals = {}
for x in df1.index.unique():
dictvals[x] = []
df2 = df1.loc[x]
if isinstance(df2, pd.DataFrame):
for idx, rowdata in df2.iterrows():
dictvals[x].append(rowdata["nextval"])
else:
dictvals[x] = df2[0]
print(dictvals)
{1: [2, 3, 6], 2: 4, 3: 5, 5: 6}
確認してくださいnetworkx
、あなたが方向グラフを必要と'root'
する'leaf'
パス
import networkx as nx
G=nx.from_pandas_edgelist(df,source='operator',target='nextval', edge_attr=None, create_using=nx.DiGraph())
road=[]
for n in G:
if G.out_degree(n)==0: #leaf
road.append(nx.shortest_path(G, 1, n))
road
Out[82]: [[1, 2, 4], [1, 3, 5, 6]]
更新
import networkx as nx
G=nx.from_pandas_edgelist(df,source='operator',target='nextval', edge_attr=None, create_using=nx.DiGraph())
road=[]
for n in G:
if G.out_degree(n)==0: #leaf
road.append(list(nx.all_simple_paths(G, 1, n)))
road
Out[509]: [[[1, 3, 5, 6], [1, 6]], [[1, 2, 4]]]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加