【问题标题】:Pythonic way to explode a bill of material (BOM) with Phyton to get a beautiful tree? I would like other solutions in pure and nice pythonic way用 Python 分解物料清单 (BOM) 以获得美丽的树的 Pythonic 方法?我想以纯正的pythonic方式获得其他解决方案
【发布时间】:2021-03-28 01:57:15
【问题描述】:

我丑陋的代码:

我只是想用字典来做这件事并得到一个 json。但我只成功地使用了 Pandas 和 Treelib。任何好的灵魂都可以给我一个关于如何以更简单的方式获得相同结果的指导吗?我的功能变得非常耗时且繁重,返回预期结果需要很长时间。 我把它放在 kaggle 中: https://www.kaggle.com/luizgustavorodrigues/bom-explosion-tree-test

import pandas as pd
from treelib import Node, Tree
from collections.abc import Iterable

### db_name = "Everest_simulator.db"
### conn = sql.connect(db_name)
### query_components = f'SELECT LTRIM(RTRIM(cd_item)) AS item, LTRIM(RTRIM(parent)) AS parent, LTRIM(RTRIM(child)) AS child, ghost, qty FROM Processo'
### df = pd.read_sql(query_components, conn)
### query_items = f'SELECT LTRIM(RTRIM(cd_item)) AS item, LTRIM(RTRIM(descricao)) AS description FROM Item'
### df_items = pd.read_sql(query_items, conn)

### Is there a way to get the result directly from SQL?

dict_components = [{'parent': 'part1', 'child': 'part2', 'ghost': 'y', 'qty': 1},
 {'parent': 'part1', 'child': 'part3', 'ghost': 'y', 'qty': 1},
 {'parent': 'part1', 'child': 'part4', 'ghost': 'n', 'qty': 1},
 {'parent': 'part2', 'child': 'part5', 'ghost': 'n', 'qty': 2},
 {'parent': 'part3', 'child': 'part6', 'ghost': 'n', 'qty': 3},
 {'parent': 'part3', 'child': 'part7', 'ghost': 'y', 'qty': 1},
 {'parent': 'part7', 'child': 'part8', 'ghost': 'n', 'qty': 4},
 {'parent': 'part7', 'child': 'part9', 'ghost': 'n', 'qty': 2},
 {'parent': 'part7', 'child': 'part10', 'ghost': 'n', 'qty': 1},
 {'parent': 'part7', 'child': 'part11', 'ghost': 'y', 'qty': 1},
 {'parent': 'part11', 'child': 'part12', 'ghost': 'n', 'qty': 3},
 {'parent': 'part11', 'child': 'part13', 'ghost': 'n', 'qty': 2},
 {'parent': 'part11', 'child': 'part14', 'ghost': 'n', 'qty': 2},
 {'parent': 'part1', 'child': 'part15', 'ghost': 'y', 'qty': 1},
 {'parent': 'part15', 'child': 'part16', 'ghost': 'n', 'qty': 2},
 {'parent': 'part15', 'child': 'part17', 'ghost': 'n', 'qty': 1},
 {'parent': 'part15', 'child': 'part18', 'ghost': 'y', 'qty': 1},
 {'parent': 'part18', 'child': 'part19', 'ghost': 'n', 'qty': 5},
 {'parent': 'part18', 'child': 'part20', 'ghost': 'n', 'qty': 2}]

df_components = pd.DataFrame.from_dict(dict_components)

dict_items = [{'item': 'part1', 'description': 'part1 description'},
 {'item': 'part2', 'description': 'part2 description'},
 {'item': 'part3', 'description': 'part3 description'},
 {'item': 'part4', 'description': 'part4 description'},
 {'item': 'part5', 'description': 'part5 description'},
 {'item': 'part6', 'description': 'part6 description'},
 {'item': 'part7', 'description': 'part7 description'},
 {'item': 'part8', 'description': 'part8 description'},
 {'item': 'part9', 'description': 'part9 description'},
 {'item': 'part10', 'description': 'part10 description'},
 {'item': 'part11', 'description': 'part11 description'},
 {'item': 'part12', 'description': 'part12 description'},
 {'item': 'part13', 'description': 'part13 description'},
 {'item': 'part14', 'description': 'part14 description'},
 {'item': 'part15', 'description': 'part15 description'},
 {'item': 'part16', 'description': 'part16 description'},
 {'item': 'part17', 'description': 'part17 description'},
 {'item': 'part18', 'description': 'part18 description'},
 {'item': 'part19', 'description': 'part19 description'},
 {'item': 'part20', 'description': 'part20 description'}]

df_items =  pd.DataFrame.from_dict(dict_items)

def get_tree_children(item_number, version=""):
    used = [item_number] # work arround to not duplicate parent nodes
    item_filter = df_components["parent"].str.strip() == item_number
    children = df_components.loc[item_filter] # Filter from thousand of data only the needed item
    for x in children.itertuples(index=True, name="Pandas"):
        if isinstance(x, Iterable): # received an Error message without this
            if x.child in used:
                pass
            else:
                used.append(x.child)
                child_item = df_items.loc[df_items['item'] == x.child] # to get the child description on df_items
                tree.create_node(
                    f"{x.child} - {child_item.description.item()} - G:{x.ghost}\t\t\t\t qty: {x.qty}",
                    f"{x.child}",
                    parent = f"{x.parent}",
                )
                get_tree_children(x.child, version="")
    return tree

item_to_tree = "part3" # interested part
tree = Tree() # create a tree named tree
tree.create_node(f"{item_to_tree}", f"{item_to_tree}") # create tree root
get_tree_children(item_to_tree) # call to get_tree_children function passing interested part
tree.show()
tree.to_json()

结果:

我返回的树:
part3
├── part6 - part6 description - G:n              qty: 3
└── part7 - part7 description - G:y              qty: 1
    ├── part10 - part10 description - G:n                qty: 1
    ├── part11 - part11 description - G:y                qty: 1
    │   ├── part12 - part12 description - G:n                qty: 3
    │   ├── part13 - part13 description - G:n                qty: 2
    │   └── part14 - part14 description - G:n                qty: 2
    ├── part8 - part8 description - G:n              qty: 4
    └── part9 - part9 description - G:n              qty: 2

我返回的json:

{
  "part3": {
    "children": [
      "part6 - part6 description - G:n\\t\\t\\t\\t qty: 3",
      {
        "part7 - part7 description - G:y\\t\\t\\t\\t qty: 1": {
          "children": [
            "part10 - part10 description - G:n\\t\\t\\t\\t qty: 1",
            {
              "part11 - part11 description - G:y\\t\\t\\t\\t qty: 1": {
                "children": [
                  "part12 - part12 description - G:n\\t\\t\\t\\t qty: 3",
                  "part13 - part13 description - G:n\\t\\t\\t\\t qty: 2",
                  "part14 - part14 description - G:n\\t\\t\\t\\t qty: 2"
                ]
              }
            },
            "part8 - part8 description - G:n\\t\\t\\t\\t qty: 4",
            "part9 - part9 description - G:n\\t\\t\\t\\t qty: 2"
          ]
        }
      }
    ]
  }
}

我希望摆脱这种情况:

“鬼”不买。只有你的孩子。 “不是鬼”是买的,你的孩子(如果存在的话)不是。 non-ghosts 的子节点仅在 BOM 中显示以供参考。

df_components - 组件数据框

parent child ghost qty
part1 part2 y 1
part1 part3 y 1
part1 part4 n 1
part2 part5 n 2
part3 part6 n 3
part3 part7 y 1
part7 part8 n 4
part7 part9 n 2
part7 part10 n 1
part7 part11 y 1
part11 part12 n 3
part11 part13 n 2
part11 part14 n 2
part1 part15 y 1
part15 part16 n 2
part15 part17 n 1
part15 part18 y 1
part18 part19 n 5
part18 part20 n 2

df_items - 项目数据框

我得到了这张表中的项目描述。主键是项目。

item description
part1 part1 description
part2 part2 description
part3 part3 description
part4 part4 description
part5 part5 description
part6 part6 description
part7 part7 description
part8 part8 description
part9 part9 description
part10 part10 description
part11 part11 description
part12 part12 description
part13 part13 description
part14 part14 description
part15 part15 description
part16 part16 description
part17 part17 description
part18 part18 description
part19 part19 description
part20 part20 description

对此:

第 3 部分的 BOM:

lvl part1_bom description qty ghost
0 0 part3 part3 description 1 y
1 1 --part6 part6 description 3 n
2 1 --part7 part7 description 1 y
3 2 ----part10 part10 description 1 n
4 2 ----part11 part11 description 1 y
5 3 ------part12 part11 description 3 n
6 3 ------part13 part11 description 2 n
7 3 ------part14 part11 description 2 n
8 2 ----part8 part8 description 4 n
9 2 ----part9 part9 description 5 n

还有这个:

根据幽灵物品的规则,这是购买的结果:

要购买的零件:

part1_parts_to_buy description qty
0 part6 part6 description 3
1 part10 part10 description 1
1 part12 part12 description 3
1 part13 part13 description 2
1 part14 part14 description 2
1 part8 part8 description 4
1 part9 part9 description 2

很抱歉这个日志问题。

【问题讨论】:

  • 我很乐意提供帮助。这听起来像是一个有趣的问题……但我会说实话。我超级困惑。尝试简化您的问题以突出您需要帮助的地方。另外,我不会读西班牙语,所以我不知道我是否遗漏了重要的部分。保持简单明了。
  • 你好 piRSquared!我将重新格式化我的问题以使其更清晰。非常感谢您有兴趣提供帮助。
  • 一般来说,这里只允许提出关于狭窄、特定错误的问题(因为 Stack Overflow 旨在成为一个巨大的常见问题解答);此外,关于如何使代码惯用的问题显然过于基于意见而不能被允许。我们的姊妹网站Code Review 允许就如何改进已经运行的代码提出一般性问题。
  • 您好 Charles Duffy,了解代码审查真是太棒了!我不知道!我所有的疑问都可以在 StackOverflow 上找到答案。非常感谢。

标签: python pandas


【解决方案1】:

基于 Code Review 成立的“trincot”先生的回复,我的执行时间从 7.2s 下降到了 0.3s。 感谢 Charles Duffy 先生和 piRSquared 先生对 cme​​ts 的帮助。

def bom_build(o,p):
    # Create a hash keyed by parts, providing their sub parts as list
    d = dict()
    for [part, subpart] in parts_h:
        if part in d:
            d[part].append(subpart)
        else:
            d[part] = [subpart]

    bom = []

    def recurse(bom, d, serial, part, path, required):
        if part in d:
            for subpart in d[part]:
                nextpath = path + '/' + subpart
                bom.append([serial, part, subpart, nextpath])
                recurse(bom, d, serial, subpart, nextpath, False)
        elif required: # when there are no sub parts
            bom.append([serial, part, None, path])

    for [serial, part] in order:
        recurse(bom, d, serial, part, part, True)

    return bom

order = [['part3','part3']] # Root part to get the BOM
parts_h = [[x['parent'],x['child']] for x in dict_components] # [['parent','child']] list of lists from my components
bom = bom_build(order,parts_h) # Calling the function
print(bom)

结果:

[['part3', 'part3', 'part6', 'part3/part6'],
 ['part3', 'part3', 'part7', 'part3/part7'],
 ['part3', 'part7', 'part8', 'part3/part7/part8'],
 ['part3', 'part7', 'part9', 'part3/part7/part9'],
 ['part3', 'part7', 'part10', 'part3/part7/part10'],
 ['part3', 'part7', 'part11', 'part3/part7/part11'],
 ['part3', 'part11', 'part12', 'part3/part7/part11/part12'],
 ['part3', 'part11', 'part13', 'part3/part7/part11/part13'],
 ['part3', 'part11', 'part14', 'part3/part7/part11/part14']]

有人可以帮我在结果中添加描述和数量吗?

我想要字典中的结果,但我不知道该怎么做。

【讨论】:

  • 一种简单(而且非常有效)的方法是通过执行df_itemsM = df_items.set_index('item')['description'].to_dict() 来构建从部分到描述的字典然后取决于您需要什么,但是例如[df_itemsM.get([part.split('\')[0],'no description') for part in order] for order in result]
  • 您好!你的回答让我很受宠若惊!我更正了我发布的结果。结果中没有/x03(我的错误)。但是,我已经在应用您的提示,如果成功,我会将其放在这里。
  • thanx,现在我看到它应该已经拆分('/')了:)要查看如何使用 df_itemsM,例如df_itemsM.get('part1','no description')
  • 您好!很有意思!感谢您的提示!
猜你喜欢
  • 2012-05-27
  • 2020-12-01
  • 1970-01-01
  • 2011-03-23
  • 2021-07-15
  • 2016-11-01
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
相关资源
最近更新 更多