如何在数据帧中行和列之间累积链接值?

2024-09-30 01:29:55 发布

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

我有一个Pandas数据框,其中每一行表示血统中两个独特点(源和目标)之间的链接。世系可能只会分裂成两个,但它们永远不会合并:

   SOURCE_ID   TARGET_ID   Splitting_event 
0  1           68          False
1  68          72          False 
2  72          75          False 
3  75          81          True 
4  75          78          True 
5  78          557         False 
6  81          85          False 
7  85          88          True 
8  85          91          True 
9  88          298         False 
10 91          99          False 
11 99          106         False 
12 106         112         True 
13 106         109         True 

我想以一种允许我跟踪每个血统的历史的方式连接分裂事件的源id

例如,查看第13行,附加列“沿袭”的理想值如下所示:

   SOURCE_ID   TARGET_ID   Splitting_event  Lineage
13 106         109         True             "75.85.106" 

到目前为止,我对嵌套for循环和条件的所有尝试都失败了,我不知道如何使用中间链接(spliting\u event=False的链接)连接所有内容。我真的很感激你的帮助

非常感谢


Tags: 数据eventidfalsetruesourcetarget目标
1条回答
网友
1楼 · 发布于 2024-09-30 01:29:55

我们需要使用df.apply的熊猫功能

def fn_apply(x):
    num = x.SOURCE_ID
    if x.SPLITTING_EVENT:
        lineage = [str(num)]
    else:
        lineage=[]
    while True:
        y = df.loc[df['TARGET_ID'] == num,:]
        if y.empty:
            break
        if y.SPLITTING_EVENT.values[0]:
            lineage.append(str(y.SOURCE_ID.values[0]))
        num = y.SOURCE_ID.values[0]
    if lineage:
        return ".".join(reversed(lineage))
    else:
        return None
df['lineage'] = df.apply(fn_apply, axis=1)
df
    SOURCE_ID   TARGET_ID   SPLITTING_EVENT     lineage
0   1           68          False               None
1   68          72          False               None
2   72          75          False               None
3   75          81          True                75
4   75          78          True                75
5   78          557         False               75
6   81          85          False               75
7   85          88          True                75.85
8   85          91          True                75.85
9   88          298         False               75.85
10  91          99          False               75.85
11  99          106         False               75.85
12  106         112         True                75.85.106
13  106         109         True                75.85.106

如果这是你想要的,请告诉我

相关问题 更多 >

    热门问题