How to find cumulative sum of items in a list of multiple dictionaries in python

Viewed 406

I have a list consisting of a dictionary (Company and Revenue). I want to run an ABC analysis on this list and am looking for the most efficient way to do it.

myList = [{"Company":"Company A", "Revenue":100}, {"Company":"Company B", "Revenue":350}, {"Company":"Company C", "Revenue":80}]

I want to use cumsum from numpy. So I first have to sort the revenue in reverse order. I would do it like this:

newList = sorted(myList, key=lambda k: k['Revenue'], reverse=True)

How do I get now the cumulative sum over the revenue in order to be able to carry out an ABC analysis?

3 Answers

Regarding what you do, Pandas seems better suited. Here is an example:

df = pd.DataFrame(myList)                             # Create a dataframe
sortedDf = df.sort_values('Revenue', ascending=False) # Sort by revenue
result = sortedDf['Revenue'].to_numpy().cumsum()      # Make the cumulative sum

print(sortedDf)
print(result)

Here is the result:

     Company  Revenue
1  Company B      350
0  Company A      100
2  Company C       80

[350 450 530]

Note that Pandas use Numpy internally for storing its columns. Note that you can make the cumulative sum directly on the dataframe to keep the meta information and do further computations.

Let us try with np.cumsum after sorting the values from the Revenue in descending order

np.cumsum(sorted([d['Revenue'] for d in myList], reverse=True))

array([350, 450, 530])

Using numpy.cumsum():

Try it online!

import numpy as np
myList = [{"Company":"Company A", "Revenue":100}, {"Company":"Company B", "Revenue":350}, {"Company":"Company C", "Revenue":80}]
newList = sorted(myList, key=lambda k: k['Revenue'], reverse=True)
a = np.array([e['Revenue'] for e in newList])
print(a.cumsum())

Output:

[350 450 530]

You can also use just Python's standard itertools.accumulate():

Try it online!

import itertools
myList = [{"Company":"Company A", "Revenue":100}, {"Company":"Company B", "Revenue":350}, {"Company":"Company C", "Revenue":80}]
newList = sorted(myList, key=lambda k: k['Revenue'], reverse=True)
a = [e['Revenue'] for e in newList]
print(list(itertools.accumulate(a)))

Output:

[350, 450, 530]
Related