对熊猫中的值求和(如果它们按层次结构排列)



我有一本字典,里面有键=父级和值=子项:

dictionary = {'100': '120', '200': '149', '760': '800', '800': '790', '150': '700', '59': '80'}

和熊猫数据帧

nodes   figures     numbers
100     triangle    0.8
120     triangle    0.2
200     square      0.3
149     square      0.2
59      square      0.9
760     circle      0.13
800     circle      0.13
790     circle      0.13
150     circle      0.13
对于

图中的每个项目,对于每个节点,如果任何节点是另一个节点的父节点,我想分配数字值的总和,如下所示

nodes   figures     numbers
100     triangle   1
120     triangle   0.2
200     square     0.5
149     square     0.2
59      square     0.9
760     circle     0.39
800     circle     0.26
790     circle     0.13
150     circle     0.13

我试过了 out = groupby(["figures"](['numbers'].sum((

但它没有返回正确的输出

figures     numbers
triangle    1
square      1.4
circle      0.52

您可以使用一个函数来执行此操作,该函数循环访问数据帧中的每一行,并以递归方式搜索子行,并随时添加值。

def get_children_values(row):
    if str(row.nodes) in dictionary: # searches for a child row
        child = df[(df.figures == row.figures) & (df.nodes.astype(str) == dictionary[str(row.nodes)])]
        if not child.empty: # if a child row is found, add its numbers value
             return row.numbers + get_children_values(child.iloc[0])
    return row.numbers  # if no child is found just return the numbers value for this row

让我们将此输出分配给一个新列进行比较:

df['new_numbers'] = df.apply(get_children_values, axis = 1)
print(df)
   nodes   figures  numbers  new_numbers
0    100  triangle     0.80         1.00
1    120  triangle     0.20         0.20
2    200    square     0.30         0.50
3    149    square     0.20         0.20
4     59    square     0.90         0.90
5    760    circle     0.13         0.39
6    800    circle     0.13         0.26
7    790    circle     0.13         0.13
8    150    circle     0.13         0.13

这应该适用于任何深度的树,但是如果您的树中有循环,这将失败并出现递归深度错误。

最新更新