1

I'm working on experimental data where I create a temperature profile from 45 °C to 5 °C and then again to 45 °C. Plotting the data results in a loop, since cooling from 45 °C to 5 °C and heating from 5° C to 45 °C are recorded. But since I need to the plot to appear "chronological" every temperature needs to be unique.

The image shows a visual explanation of what I need. Visual explanation

What I did therefore is getting the difference from each consecutive temperature interval using numpys "diff" function. So far so good. Now to make a useful plot out of this I need to somehow create a new list where every item is the sum from the ones before.

A small example of what I'm looking for:

my_list = [1,2,5,1,4,2,3]
#some operation
result_list = [1,3,8,9,13,15,18]

Would be great if someone knows how to do that or has a smarter idea how to get the job done!

Joscha Kruse
  • 285
  • 1
  • 3
  • 6

3 Answers3

6

Since this question is tagged numpy but for some reason nobody posts the numpy solution... use numpy.cumsum. :)

>>> my_list = [1,2,5,1,4,2,3] # could also be a numpy array
>>> np.cumsum(my_list)
array([ 1,  3,  8,  9, 13, 15, 18])
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

There is a nice feature from itertools called accumulate that does exactly that:

from itertools import accumulate

lst = [1,2,5,1,4,2,3]
result_list = list(accumulate(lst))
print(result_list)  # -> [1, 3, 8, 9, 13, 15, 18]
Ma0
  • 15,057
  • 4
  • 35
  • 65
0
my_list = [1,2,5,1,4,2,3]
result_list = [my_list[0]]

for i in my_list[1:]:
    result_list.append(result_list[-1] + i)

This should do the trick.