我有数据:

issue father son
1 33 34
1 34 35
2 33 34

以下是Python中的脚本,它按层次 struct 检索表:

G = nx.from_pandas_edgelist(df, source='father', target='son', create_using=nx.DiGraph ,edge_attr=True)
print(G.out_degree())
roots = [v for v, d in G.in_degree() if d == 0]
leaves = [v for v, d in G.out_degree() if d == 0]
all_paths = []
for root in roots:
    for leaf in leaves:
        paths = nx.all_simple_paths(G, root, leaf)
        all_paths.extend(paths)
for node in nx.nodes_with_selfloops(G):
    all_paths.append([node, node])
df_h=pd.DataFrame(sorted(all_paths)).add_prefix('Value_Depend_On_ID_').fillna('')
df_h=df_h.replace('',np.nan, regex=True)
df_h.astype('Int64')

输出:

Value_Depend_On_ID_0 Value_Depend_On_ID_1 Value_Depend_On_ID_2
33 34 35

所需的输出:

Value_Depend_On_ID_0 Value_Depend_On_ID_1 Value_Depend_On_ID_2 issue
33 34 35 1
33 34 null 2

如何添加问题?

推荐答案

如果我理解正确的话,您希望将数据帧按issue分组,然后搜索所有路径:

import networkx as nx


def group_func(g):
    G = nx.from_pandas_edgelist(
        g, source="father", target="son", create_using=nx.DiGraph
    )

    roots = [v for v, d in G.in_degree() if d == 0]
    leaves = [v for v, d in G.out_degree() if d == 0]

    all_paths = []
    for root in roots:
        for leaf in leaves:
            paths = nx.all_simple_paths(G, root, leaf)
            all_paths.extend(paths)

    out = []
    for p in all_paths:
        d = {}
        for i, v in enumerate(p):
            d[f"Value_Depend_On_ID_{i}"] = v
        out.append(d)

    return pd.DataFrame(out)


x = (
    df.groupby("issue")
    .apply(group_func, include_groups=False)
    .reset_index(1, drop=True)
    .reset_index()
)
print(x)

打印:

   issue  Value_Depend_On_ID_0  Value_Depend_On_ID_1  Value_Depend_On_ID_2
0      1                    33                    34                  35.0
1      2                    33                    34                   NaN

Python相关问答推荐

滚动和,句号来自Pandas列

比较2 PD.数组的令人惊讶的结果

查找两极rame中组之间的所有差异

将输入管道传输到正在运行的Python脚本中

2D空间中的反旋算法

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

什么是最好的方法来切割一个相框到一个面具的第一个实例?

索引到 torch 张量,沿轴具有可变长度索引

如何更新pandas DataFrame上列标题的de值?

旋转多边形而不改变内部空间关系

Flash只从html表单中获取一个值

Python Pandas—时间序列—时间戳缺失时间精确在00:00

如何删除重复的文字翻拍?

如何在GEKKO中使用复共轭物

仅使用预先计算的排序获取排序元素

如何将泛型类类型与函数返回类型结合使用?

如何在Quarto中的标题页之前创建序言页

正则表达式反向查找

Django-修改后的管理表单返回对象而不是文本

如何定义一个将类型与接收该类型的参数的可调用进行映射的字典?