在熊猫数据框中识别最终父母

时间:2018-11-22 16:31:26

标签: python pandas loops dataframe for-loop

我有以下数据帧,其中有一个列Child和一个列Parents

import pandas as pd
df = pd.DataFrame({'Child': ['A1', 'A2', 'A3', 'A1', 'A1', 'A4', 'A2', 'A3'],
               'Parent': ['B1', 'B2', 'A2', 'B3', 'A4', 'B4', 'B5', 'B6']})

df

  Child Parent
0    A1     B1
1    A2     B2
2    A3     A2
3    A1     B3
4    A1     A4
5    A4     B4
6    A2     B5
7    A3     B6

有重复的children,其中一些出现在parent列中。我想知道最终的父母。这是与this one类似的问题,但在Child列中有重复项。我想要的输出如下所示:

  Child                                  Links   Ult_Parents
0    A1       (A1 - B1, A1 - B3, A1 - A4 - B4)  (B1, B3, B4)
1    A2                     (A2 - B2, A2 - B5)      (B2, B5)
2    A3  (A3 - A2 - B2, A3 - A2 - B5, A3 - B6)  (B2, B5, B6)
3    A4                              (A4 - B4)          (B4)

A1具有明确的父级B1和B3,但还有B4,因为它链接到A4。 A2仅具有B2和B5。我对它们之间的链接很感兴趣,但主要是对最终的父母。

1 个答案:

答案 0 :(得分:2)

import networkx as nx
def all_descendants_nx():
    DiG = nx.from_pandas_edgelist(df,'Parent','Child',create_using=nx.DiGraph())
    return pd.DataFrame.from_records([(n1,n2) for n1 in DiG.nodes() for n2 in nx.ancestors(DiG, n1)], columns=['Child','Ult_Parents'])

df = all_descendants_nx()
df = df.loc[df.Ult_Parents.str.startswith("B")]
print(df)

df['Links'] = df.Child.astype('str') + ' - ' + df.Ult_Parents.astype('str')
df = df.groupby('Child').agg(lambda x: sorted(x.tolist())).reset_index()
print(df)