【问题标题】:Easier way to find nodes in a dataframe在数据框中查找节点的更简单方法
【发布时间】:2023-04-10 12:26:01
【问题描述】:

给定一个父节点,我想获取它的 N 级节点(原始数据框要大得多)

child|   level|  parent|
   40|       1|      40|
   21|       2|      40|
   18|       2|      40|
   37|       3|      21|
    2|       3|      18|
   85|       3|      21|
   14|       4|      37|
   58|       4|       2|
   47|       4|      37|
   34|       4|      85|
   45|       4|      18|
   32|       4|       2|
   47|       4|      85|
   88|       4|      85|
   12|       4|      37|

我做什么:

def get_children(x, tree, lst):
    for nod in tree[tree['parent'] == x]['child']:
        get_children(nod, tree, lst)
        lst.append(nod)

然后我过滤所有N级节点。

我想要另一种方式,因为当数据框较大时,递归调用过多。

【问题讨论】:

    标签: python-3.x pandas algorithm recursion


    【解决方案1】:

    使用辅助数据结构,您可以分两步解决此任务:

    1. 存储每个节点的所有前任
    2. 对于每个级别 N 的节点,检查节点 x 是否在前辈列表中

    如果没有进一步的假设(例如,邻接列表是有序的,并且更高级别的节点不能是低级别节点的父节点),您将需要循环遍历列表至少两次(一次创建父索引,然后再一次每次查找)。但是,如果可以做出上述假设,则单个循环就足够了。

    # determine all predecessors of each node in tree
    def index_parents(tree):
      parents = {}
      for i, n in tree.iterrows():
        child = int(n['child']) 
        parent = int(n['parent'])
        # if this child node is seen for the first time, initialize parents
        if child not in parents: 
          parents[child] = set()
        # add current parent to predecessor list
        parents[child].update(set([parent]))
        # add predecessors of parent to predecessor list
        parents[child].update(parents[parent])
    
      return parents
    
    # check all nodes at given level if they contain x as predecessor
    def get_children(x, tree, level, parents):
      x_children = []
      for i, n in tree.iterrows():
        child = int(n['child'])
        if n['level'] == level and x in parents[child]:
          # x is in predecessors of child, add it to the result
          x_children.append(child)
    
      return x_children
    

    给你测试数据的测试:

    >>> parents = index_parents(tree)
    >>> get_children(21, tree, 3, parents)                                                                                    
    >>> [37, 85]
    

    它可能看起来有点倒退,但它避免了递归。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2011-09-05
    • 2010-10-14
    • 2015-09-20
    • 2012-11-19
    相关资源
    最近更新 更多