2 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
這是一個(gè)樹結(jié)構(gòu),一種特殊類型的圖。數(shù)據(jù)框并不是表示樹的特別方便的方式;我建議您切換到networkx或其他一些基于圖形的包。然后查找如何進(jìn)行簡(jiǎn)單的路徑遍歷;您會(huì)在圖形包文檔中找到直接支持。
如果你堅(jiān)持自己做——這是一個(gè)合理的編程練習(xí)——你只需要像這樣的偽代碼
for each parent not in "child" column:
here = parent
while here in parent column:
here = here["child"]
record (parent, here) pair

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
雖然您的預(yù)期輸出似乎與您的描述有些不一致(AC2 似乎不應(yīng)該被視為父節(jié)點(diǎn),因?yàn)樗皇窃垂?jié)點(diǎn)),但我非常有信心您想從每個(gè)源節(jié)點(diǎn)運(yùn)行遍歷以定位它所有的葉子。在數(shù)據(jù)框中這樣做并不方便,因此我們可以使用df.values
并創(chuàng)建一個(gè)鄰接列表字典來(lái)表示圖形。我假設(shè)圖中沒(méi)有循環(huán)。
import pandas as pd
from collections import defaultdict
def find_leaves(graph, src):
? ? if src in graph:
? ? ? ? for neighbor in graph[src]:
? ? ? ? ? ? yield from find_leaves(graph, neighbor)
? ? else:
? ? ? ? yield src
def pair_sources_to_leaves(df):
? ? graph = defaultdict(list)
? ? children = set()
? ? for parent, child in df.values:
? ? ? ? graph[parent].append(child)
? ? ? ? children.add(child)
? ? leaves = [[x, list(find_leaves(graph, x))]?
? ? ? ? ? ? ? ?for x in graph if x not in children]
? ? return (pd.DataFrame(leaves, columns=df.columns)
? ? ? ? ? ? ? .explode(df.columns[-1])
? ? ? ? ? ? ? .reset_index(drop=True))
if __name__ == "__main__":
? ? df = pd.DataFrame({
? ? ? ? "parent": ["AC1", "AC2", "AC3", "AC1", "AC11",?
? ? ? ? ? ? ? ? ? ?"AC5", "AC5", "AC6", "AC8", "AC9"],
? ? ? ? "child": ["AC2", "AC3", "AC4", "AC11", "AC12",?
? ? ? ? ? ? ? ? ? "AC2", "AC6", "AC7", "AC9", "AC10"]
? ? })
? ? print(pair_sources_to_leaves(df))
輸出:
? parent child
0? ? AC1? ?AC4
1? ? AC1? AC12
2? ? AC5? ?AC4
3? ? AC5? ?AC7
4? ? AC8? AC10
添加回答
舉報(bào)