1

I'm working with python and I read out a column from a CSV file. I save the values in an array by grouping them. This array looks something like this:

[1, 5, 10, 15, 7, 3]

I want to create a second array where I take the number of the array and make the sum with the previous values. So in this case I would like the have the following output:

[1, 6, 16, 31, 38, 41]

My code is as follows:

import csv
import itertools

with open("c:/test", 'rb') as f:
    reader = csv.reader(f, delimiter=';')

    data1 = []
    data2 = []

    for column in reader:
        data1.append(column[2])

    results = data1
    results = [int(i) for i in results]
    results = [len(list(v)) for _, v in itertools.groupby(results)]
    print results

    data2.append(results[0])
    data2.append(results[0]+results[1])
    data2.append(results[0]+results[1]+results[2])
    print data2

So I can make the array by doing it manually, but this costs a lot of time and is probably not the best way to do it. So what is the best way to do something like this?

1

3 Answers 3

3

You are looking for the cumulative sum of a list. The easiest way is to let numpy do it.

>>> import numpy as np
>>> np.cumsum([1, 5, 10, 15, 7, 3])
array([ 1,  6, 16, 31, 38, 41])
Sign up to request clarification or add additional context in comments.

3 Comments

Stupid question, why there are 2 whitespaces before '6'?
That's just how my REPL decided to print it.
Thing is, mine also and it makes no sense hah
1
a = [1, 5, 10, 15, 7, 3]
b = [a[0]]
for i in range(1, len(a)):
    b.append(b[-1]+ a[i])

a is your column from .csv. b is a list with already one value in it, which is first item of a. Then we loop through a starting from it's second item and we add the consequent values from it to last item of b and append it to b.

Comments

0

Using your code objects, what you look for would be something like:

from __future__ import print_function

import csv
import itertools

"""
with open("c:/test", 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    for column in reader:
        data1.append(column[2])
"""

data1 = [1, 5, 10, 15, 7, 3]

results = [data1[0]]

for i in range(1, len(data1)):
    results.append(results[i-1] + data1[i])

print(data1, results)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.