递归Excel文件以从树结构中查找顶级项目

时间:2018-03-17 21:26:36

标签: python python-3.x pandas recursion tree

我正在尝试递归数据集以找到最高级别的项目,即没有父项目的项目。

结构如下:

╔════════════╦════════════╗
║    Item    ║  Material  ║
╠════════════╬════════════╣
║ 2094-00003 ║ MHY00007   ║
║ 2105-0001  ║ 2105-0002  ║
║ 2105-0002  ║ 2105-1000  ║
║ 2105-1000  ║ 2105-1003  ║
║ 2105-1003  ║ 7547-122   ║
║ 7932-00001 ║ 7932-00015 ║
║ 7932-00002 ║ 7932-00015 ║
║ 7932-00010 ║ MHY00007   ║
║ 7932-00015 ║ 7932-05000 ║
║ 7932-05000 ║ MHY00007   ║
╚════════════╩════════════╝

因此,例如,如果我选择7547-122,该函数将返回2105-0001。因此该函数递归地跟随树向上,7547-122 - > 2105-1003 - > 2105-1000 - > ... - > 2105-0001。

当我运行我的代码时,我只能让它返回一个顶层,正如你从MHY00007案例中看到的那样,有时会有多个顶层。如何返回任何给定材料的所有顶级列表?

我的代码:

import pandas as pd


class BillOfMaterials:

    def __init__(self, bom_excel_path):
        self.df = pd.read_excel(bom_excel_path)
        self.df = self.df[['Item', 'Material']]

    def find_parents(self, part_number):
        material_parent_search = self.df[self.df.Material == part_number]

        parents = list(set(material_parent_search['Item']))

        return parents

    def find_top_levels(self, parents):

        top_levels = self.__ancestor_finder_([parents])

        print(f'{parents} top level is {top_levels}')
        return {parents: top_levels}

    def __ancestor_finder_(self, list_of_items):

        for ancestor in list_of_items:
            print(f'Searching for ancestors of {ancestor}')
            ancestors = self.find_parents(ancestor)
            print(f'{ancestor} has ancestor(s) {ancestors}')

            if not ancestors:
                return ancestor
            else:
                highest_level = self.__ancestor_finder_(ancestors)
        return highest_level


BOM = BillOfMaterials(bom_excel_path="Path/To/Excel/File/BOM.xlsx")

ItemsToSearch = ['7547-122', 'MHY00007']

top_levels = []
for item in ItemsToSearch:
    top_levels.append(BOM.find_top_levels(item))

2 个答案:

答案 0 :(得分:2)

是的,您可以递归执行此操作,例如:

import pandas as pd


class BillOfMaterials:

    def __init__(self, bom_excel_path):
        self.df = pd.read_excel(bom_excel_path)
        self.df = self.df[['Item', 'Material']]

    def find_parents(self, part_number):
        return list(set(self.df[self.df.Material == part_number]['Item']))

    def find_top_levels(self, item):
        parents = self.find_parents(item)
        if not parents:
            # there are no parent items => this item is a leaf
            return [item]
        else:
            # there are parent items => recursively find grandparents
            grandparents = []
            for parent in parents:
                grandparents = grandparents + self.find_top_levels(parent)
            return grandparents


if __name__ == '__main__':
    BOM = BillOfMaterials(bom_excel_path="testdata.xlsx")
    ItemsToSearch = ['7547-122', 'MHY00007']

    for i in ItemsToSearch:
        print('')
        print('The top levels of ' + i + ' are: ')
        print(BOM.find_top_levels(i))

请注意self.find_top_levels(parent)的递归调用。 这将给出输出

The top levels of 7547-122 are: 
['2105-0001']

The top levels of MHY00007 are: 
['2094-00003', '7932-00001', '7932-00002', '7932-00010']

答案 1 :(得分:1)

pandas数据框的递归速度比使用dict慢。

为了提高性能,我建议您创建一个字典并创建一个简单的函数来迭代循环树结构。以下是一个例子。

import pandas as pd

df = pd.DataFrame({'Item': ['2094-00003', '2105-0001', '2105-0002', '2105-1000',
                            '2105-1003', '7932-00001', '7932-00002', '7932-00010',
                            '7932-00015', '7932-05000'],
                   'Material': ['MHY00007', '2105-0002', '2105-1000', '2105-1003',
                                '7547-122', '7932-00015', '7932-00015', 'MHY00007',
                                '7932-05000', 'MHY00007']})

parent_child = df.set_index('Item')['Material'].to_dict()
child_parent = {v: k for k, v in parent_child.items()}

def get_all_parents(x):
    while x in child_parent:
        x = child_parent[x]
        yield x

def get_grand_parent(x):
    for last in get_all_parents(x):
        pass
    return last

get_grand_parent('7547-122')
# '2105-0001'