如何组合父子关系上的两个数据帧(concat和merge之间的一些东西)

2024-10-17 08:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力形成一个树状的数据帧,其中子行正好位于其父对象的下方。我要做的是在对象\u id x父项\u id上合并和沿着轴0连接。 所以我要找的是下面代码片段中interlace函数的实现。在

In[1]: parents = pd.DataFrame({'object_id':[1,2],
                               'parent_id':[0,0],
                               'position': [1,2]})

In[2]: parents

Out[2]    object_id     parent_id   position
       0  1             0           1
       1  2             0           2

In[3]: children = pd.DataFrame({'object_id':[3,4,5],
                                'parent_id':[1,1,2],
                                'position': [1,2,1]})

In[4]: children

Out[4]:   object_id     parent_id   position
       0  3             1           1
       1  4             1           2
       2  5             2           1

In[5]: interlace(parent, children, on=('object_id', 'parent_id'))

Out[5]:  object_id  parent_id   position
      0  1          0           1
      1  3          1           1
      2  4          1           2
      3  2          0           1
      4  5          2           1

在大熊猫身上有没有一种有效的方法? 我想你可以做点什么

^{pr2}$

但我觉得应该有更简单、更有效的方法来做到这一点。在

编辑:具有相同级别和相同父级的行需要按其位置进行排序。在


Tags: 数据对象方法iniddataframeobjectposition