python - 如何在父子关系上组合两个数据帧(介于连接和合并之间)

标签 python pandas merge concatenation

我正在努力形成一个像数据框一样的树,其中子行就在其 parent 的下方。我想做的是合并 object_id xparent_id 和沿轴 0 连接之间的事情。 所以我正在寻找的是下面代码片段中交错函数的实现。

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

有没有一种有效的方法可以在 pandas 中做到这一点? 我认为人们可以做类似的事情

parents_with_children = []
for i, parentrow in parents.iteritems():
    childrenrows = children[children.parent_id == parentrow.object_id]
    parents_with_children.append(pd.concat([parentrow, childrenrows])
result = pd.concat(parents_with_children)

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

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

最佳答案

可能的解决方案:

children['sort_id']=children.parent_id
parents['sort_id']=parents.object_id
pd.concat([parents,children]).sort_values(['sort_id', 'parent_id']).drop('sort_id', 1)

关于python - 如何在父子关系上组合两个数据帧(介于连接和合并之间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40727148/

相关文章:

python - Pandas :将特定行更改为百分比

python - 使用pandas,找到两个DataFrame之间的相交区域?

svn - 合并到分支时发生冲突,删除代码中的一些更改

python - 相当于 tensorflow 中的 np.add.at

python - 是否可以以编程方式从数据包创建请求?

python - 为图例后绘图添加标签

excel - df.loc 具有跨两个不同数据源的两个条件

python - 无法使用 scipy.arff.loadarff 加载 arff 数据集

python - 在 Pandas 中,如何在 groupby.agg() 方法中应用 2 个自定义公式?

MySQL 查询 : Merge Results