我是如何循环检查df中每行的值以检查该值是否满足条件的

2024-09-30 16:27:47 发布

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

我的表格如下:

ID   IsCreated  ParentID
101  0          NA
102  1          101
103  0          NA
104  1          102
105  1          104

我想添加一个名为“OGParentID”的新列,其结果如下所示:

ID   IsCreated  ParentID   OGParentID
101  0          NA         101        
102  1          101        101        
103  0          NA         103        
104  1          102        101        
105  1          104        101  

  

这里使用的逻辑如下: 对于每一行,检查IsCreated=1,如果是,则在ID列中查找ParentID以检查IsCreated是否为0,如果是,则将OGParentID设置为已查找的父ID,否则,检查已查找的ParentID的父ID并继续循环


Tags: id逻辑表格naparentidiscreatedogparentid
2条回答

你可以做:

#creating a dictionary "x" to have all the unique parent-child relationships using comprehension
x={i:int(j) for i,j in zip(df['ID'],df['ParentID'].fillna(df['ID']))}

#assigning ID to the new column 
df['OGParentID']=df['ID']

#loop to replace the dict items ,i.e, replacing all the childs with parents
#counter is limited to the length of unique elements in dict
i=0
while i<=len(x):
    df['OGParentID']=df['OGParentID'].replace(x)
    i+=1


Output: 

        ID  IsCreated  ParentID  OGParentID
    0  101          0       NaN         101
    1  102          1     101.0         101
    2  103          0       NaN         103
    3  104          1     102.0         101
    4  105          1     104.0         101

您可以编写一个函数,然后将其应用于列

def lookup(parent_id):
    while True:
        # find the row where ID is equal to the parent_id
        temp = df[df[‘ID’]==parent_id]
        # check if iscreated is 0, return the parent_id if it is 0
        if temp[‘IsCreated’][0]==0:
            return parent_id
        # at this point, iscreated must be 1, so now we set parent_id to the ParentID in this row and do it again until we find iscreated is 0.
        parent_id = temp[‘ParentID’]

df[‘OGParentID’] = df[‘ParentID’].apply(lookup)


此代码将获取每个ParentID并将其提供给函数lookup

函数lookup根据OP的要求执行以下操作:

  1. 查找ID等于给定父项ID的行
  2. 检查iscreated是否为0。如果是,则返回此行的ParentID
  3. 如果没有,请将parent_id设置为此行的ParentID,并重复步骤1

相关问题 更多 >