2

So I'm a little lost here. I have a numpy array that contains multiple array within it. My goal is to sum all of the arrays INSIDE of the big array, resulting in a singular array containing those summed values.

I've already tried using np.sum() but this goes one step too far and sums everything returning a single integer value.

an example of what I am trying to accomplish: a = (array([1, 2, 3]), array([3, 4, 5])) **perform some steps and the desired result is: a = (array([4, 6, 8]))

hpaulj
  • 221,503
  • 14
  • 230
  • 353
noamb
  • 21
  • 1
  • "I have a numpy array that contains multiple array within it." What? So your array's `dtype` is object? Please provide a [mcve] Note, `a = (array([1, 2, 3]), array([3, 4, 5]))` is not an array that contains a number of arrays. It is a tuple with array objects inside of it. – juanpa.arrivillaga Jan 25 '19 at 21:52
  • let's be clear - is this a multidimensional array of numbers, or an object dtype array containing arrays? The difference is important, but your description is vague. Did you read about the `axis` parameter for `sum`? – hpaulj Jan 25 '19 at 23:14
  • Are all the arrays inside of the same length? – user8408080 Jan 26 '19 at 01:31

3 Answers3

2

You can directly use the summation operation for this purpose. You don't need any specific built-in function to do this task.

import numpy as np

a = (np.array([1,2,3]), np.array([3,4,5])))
sum = a[0] + a[1]
print('The summation of two sub-arrays: ',sum)

After the above code is interpreted, you will get a result like this;

The summation of two sub-arrays: [4 6 8]

Ozan Yurtsever
  • 1,274
  • 8
  • 32
1

UPDATE: Better solution w/ vectorized addition

#!/usr/bin/env python3

import numpy as np

a = (np.array([1,2,3]), np.array([3,4,5]))
print(sum(a))
>>> [4 6 8]

Original, clumsy, non numpyic solution

#!/usr/bin/env python3
import numpy as np
a = (np.array([1,2,3]), np.array([3,4,5]))  
b = zip(*a) 
c = [sum(arr) for arr in b]
print(c)
>>> [4, 6, 8]
d = np.array(c)
print(d)
>>> [4 6 8]
Scott Skiles
  • 3,647
  • 6
  • 40
  • 64
  • 1
    Why wouldn't you just add up the arrays? Why the transpose using `zip` then a list-comprehension wiht `sum`? Just `a[0] + a[1]` or even `sum(a)` would work – juanpa.arrivillaga Jan 25 '19 at 21:55
  • Does that work for any number of np.arrays? Makes sense! +1 vectorized operations :-) – Scott Skiles Jan 25 '19 at 22:02
  • Thanks @juanpa.arrivillaga! Yeah I ended up using the sum function because I had many sub-arrays worked great. Thank you all for the feedback! :) – noamb Jan 25 '19 at 23:17
0

You definitely need to iterate through np lists elements so check this for iterating pairwise and secondly check this sum list's elements

TassosK
  • 293
  • 3
  • 16