我有一个数据集,其值在不同的行中都是父项和子项。父母和孩子之间的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
因此整个文件,成千上万的行,都遵循这种格式,首先列出一个父级,然后是所有子级,然后是下一个父级。
您当然可以使用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