'Python Adding values of leaves to nodes
I'm working with the following dataframe:
ID Value
01.1 0.0
01.1.1 0.0
01.1.1.01 0.0
01.1.1.01.001 27508.42
01.1.1.01.002 24170.31
01.1.1.02 25861.82
01.1.1.04 0.0
01.1.1.04.001 0.0
01.1.1.04.001.001 28906.54
01.1.1.04.001.002 30396.25
The ID is a string. Is there a way to sum the values of the 'leaves' to the 'node' before? I know this is not a tree For example:
ID Value
01.1.1.04.001 59302.79
The schema:
1
├── 1.1
├── 1.2
│ ├── 1.2.1
│ └── 1.2.2
└── 1.3
└── 1.3.1
├── 1.3.1.1
└── 1.3.1.3
Solution 1:[1]
Let's do it easier.
We can create a new column in your dataframe with the length of 'ID':
your_df_name['level']=your_df_name['ID'].str.len()
We use groupby now:
your_df_name.groupby(by='level').agg({'value': ['sum']})
The 'level' will not be descriptive, so you can add a new column with the schema values based on its lenght.
It should be fine.
Saying “thanks” is appreciated, but it doesn’t answer the question. Instead, vote up the answers that helped you the most! If these answers were helpful to you, please consider saying thank you in a more constructive way – by contributing your own answers to questions your peers have asked here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
