I have this dataframe (ID is a string and Value a float):

ID              Value
1               0.0
1.1             0.0
1.2             0.0
1.2.1           27508.42
1.2.2           25861.82
1.3             0.0
1.3.1           0.0
1.3.1.1         0.0
1.3.1.2         0.0
1.3.1.3         30396.25

Whose structure works like this:

1
├── 1.1  
├── 1.2  
│   ├── 1.2.1  
│   └── 1.2.2  
└── 1.3  
    └── 1.3.1  
        ├── 1.3.1.1
        ├── 1.3.1.2    
        └── 1.3.1.3  

And need for the value of the 'parent' node to be the sum of the leaves. So:

ID              Value
1               83766.489    (1.1 + 1.2 + 1.3)
1.1             0.0
1.2             53370.24     (1.2.1 + 1.2.2)
1.2.1           27508.42
1.2.2           25861.82
1.3             30396.25     (1.3.1)
1.3.1           30396.25     (1.3.1.1 + 1.3.1.2 + 1.3.1.3)
1.3.1.1         0.0
1.3.1.2         0.0
1.3.1.3         30396.25

How can I group the IDs? Using groupby wont work since all the IDs are unique. Should I change the structure of the dataframe to better reflect the logic of the schema?

推荐答案

Another solution (assuming column ID is sorted):

def counter(x):
    out = []
    for id_, v in zip(x.index, x):
        s = sum(
            v
            for a, v in out
            if a.startswith(id_) and id_.count(".") == a.count(".") - 1
        )
        out.append((id_, s + v))
    return [v for _, v in out]


print(df.set_index("ID")[::-1].apply(counter)[::-1].reset_index())

Prints:

        ID     Value
0        1  83766.49
1      1.1      0.00
2      1.2  53370.24
3    1.2.1  27508.42
4    1.2.2  25861.82
5      1.3  30396.25
6    1.3.1  30396.25
7  1.3.1.1      0.00
8  1.3.1.2      0.00
9  1.3.1.3  30396.25

Python相关问答推荐

如何找到满足各组口罩条件的第一行?

Python库:可选地支持numpy类型,而不依赖于numpy

对所有子图应用相同的轴格式

运输问题分支定界法&

如果值发生变化,则列上的极性累积和

在pandas中使用group_by,但有条件

改进大型数据集的框架性能

需要帮助重新调整python fill_between与数据点

numpy.unique如何消除重复列?

pandas:在操作pandora之后将pandora列转换为int

Python—在嵌套列表中添加相同索引的元素,然后计算平均值

如何使用加速广播主进程张量?

从列表中分离数据的最佳方式

根据过滤后的牛郎星图表中的数据计算新系列

如何在Python中实现高效地支持字典和堆操作的缓存?

如何将django url参数传递给模板&S url方法?

如何使用count()获取特定日期之间的项目

如何将参数名作为参数传入到函数中?

`Convert_time_zone`函数用于根据为极点中的每一行指定的时区检索值

SQL模型中包含日期时间的TypeError