亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

熊貓數據框中的遞歸函數

熊貓數據框中的遞歸函數

瀟湘沐 2023-05-16 15:52:19
我創建了以下數據框import pandas as pd    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']})輸出以下內容:    parent  child0   AC1     AC21   AC2     AC32   AC3     AC43   AC1     AC114   AC11    AC125   AC5     AC26   AC5     AC67   AC6     AC78   AC8     AC99   AC9     AC10我想創建一個結果數據框,其中列出了每個父項(意味著它不存在于子列中)和最后一個子項。df_result = pd.DataFrame({'parent': ['AC1', 'AC1', 'AC5', 'AC5', 'AC8', 'AC2'],                     'child': ['AC4', 'AC12', 'AC4', 'AC7', 'AC10', 'AC4']})    parent  child0   AC1     AC41   AC1     AC122   AC5     AC43   AC5     AC74   AC8     AC105   AC2     AC4我已經啟動了以下功能,但我不確定如何完成它。def get_child(df):result = {}if df['parent'] not in df['child']:    return result[df['parent']]
查看完整描述

2 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

這是一個樹結構,一種特殊類型的圖。數據框并不是表示樹的特別方便的方式;我建議您切換到networkx或其他一些基于圖形的包。然后查找如何進行簡單的路徑遍歷;您會在圖形包文檔中找到直接支持。


如果你堅持自己做——這是一個合理的編程練習——你只需要像這樣的偽代碼


for each parent not in "child" column:

    here = parent

    while here in parent column:

        here = here["child"]


    record (parent, here) pair


查看完整回答
反對 回復 2023-05-16
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

雖然您的預期輸出似乎與您的描述有些不一致(AC2 似乎不應該被視為父節點,因為它不是源節點),但我非常有信心您想從每個源節點運行遍歷以定位它所有的葉子。在數據框中這樣做并不方便,因此我們可以使用df.values并創建一個鄰接列表字典來表示圖形。我假設圖中沒有循環。


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


查看完整回答
反對 回復 2023-05-16
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號