McLeodx - 10 months ago 35

Python Question

Using Python, I have a list of two-element dictionaries which I would like to sum all the values of one element based upon the values of another element. ie.

`[{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}]`

This is the format (although there are much more entries than this), and for each different

`elev`

`area`

`elev`

`0.0`

`elev`

`0.1`

Answer Source

this is very easily achieved using pandas. Sample code:

```
import pandas as pd
df = pd.DataFrame([{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}])
```

which gives the following dataframe:

```
area elev
0 3.523558 0.0
1 3.523558 0.0
```

Then group by the elev columns and sum the area's:

```
desired_output = df.groupby('elev').sum()
```

which gives:

```
area
elev
0.0 7.047115
```

If you want you can then output this dataframe back to a dictionary in a useful format using:

```
desired_output.to_dict('index')
```

which returns

```
{0.0: {'area': 7.0471151003078063}}
```