Josh Goldsmith
Josh Goldsmith

Reputation: 65

Adding together values in 2 different arrays to calculate an average python

I have two arrays that need to be combined into a single array by adding the together the values from each array.

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]

x = np.sum(a, b)

the result I want is:

x = [2, 4, 6, 8, 10]

then to be able to calculate the average of each value to get results:

x = [1, 2, 3, 4, 5] 

When I run that, it returns the error

TypeError: 'list' object cannot be interpreted as an integer

Upvotes: 0

Views: 1578

Answers (2)

Prune
Prune

Reputation: 77837

sum takes the sum of a sequence of objects. For instance, sum(a) would yield the value 15. You gave it two lists.

Since you want to add two arrays, you need to convert the lists to numpy arrays first; then you can add them as a numpy vector addition.

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> b = np.array([1, 2, 3, 4, 5])
>>> a+b
array([ 2,  4,  6,  8, 10])
>>> (a+b)/2
array([ 1.,  2.,  3.,  4.,  5.])

Upvotes: 2

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

Use some good ole list comprehension. The zip function will also help us in this case.

result = [x+y for x, y in zip(a,b)]

Zip joins each element of x to an element of y at the same index and stops when one list runs out. List comprehension takes each element in the newly created list and adds the two that are next to each other together.

So it looks like this expanded:

for n,z in zip(x,y):
    x.append(n+z)

example:

> a = b = [1,2,3,4,5]
> result = [x+y for x, y in zip(a,b)]
> result
[2, 4, 6, 8, 10]

Upvotes: 1

Related Questions