熊猫,每x行取决于另一行的值

时间:2020-04-08 00:44:01

标签: pandas

我有一个数据集,其值在不同的行中都是父项和子项。父母和孩子之间的ID格式略有不同,因此我应该可以使用正则表达式来识别它们。

所以结构是这样的

Parent ID | Other data
Child ID | Other data
Child ID | Other data
Child ID | Other data
Parent ID | Other data
Child ID | Other data
Parent ID | Other data
Child ID | Other data
Child ID | Other data
Child ID | Other data

没有固定数量的子代,但是唯一正确的是父代首先出现,然后是子代,然后是下一个父代,也就是子代,依此类推。

我不确定该如何识别。理想情况下,我将能够遍历所有行,并在另一行(新行)中用父母的ID标记所有孩子。

这不是一个很好的结构,但是它来自数据源。

我想要这样的输出

Parent ID | Other data
Child ID | Other data | Parent ID
Child ID | Other data | Parent ID
Child ID | Other data | Parent ID
Parent ID | Other data | 
Child ID | Other data | Parent ID
Parent ID | Other data |
Child ID | Other data | Parent ID
Child ID | Other data | Parent ID
Child ID | Other data | Parent ID

因此,整个文件(成千上万行)都遵循这种格式,首先列出父级,然后是所有子级,然后是下一个父级。

1 个答案:

答案 0 :(得分:0)

您当然可以使用ffill和一些遮罩来实现

# identify all parents
# replace with your regex
patt = '(Parent)'
is_parent = df['ID'].str.extract(patt).notnull()[0]

# ids:
df['parent_ID'] = df['ID'].where(is_parent).ffill().mask(is_parent)

输出:

          ID        data   ParentID
0  Parent ID  Other data        NaN
1   Child ID  Other data  Parent ID
2   Child ID  Other data  Parent ID
3   Child ID  Other data  Parent ID
4  Parent ID  Other data        NaN
5   Child ID  Other data  Parent ID
6  Parent ID  Other data        NaN
7   Child ID  Other data  Parent ID
8   Child ID  Other data  Parent ID
9   Child ID  Other data  Parent ID