I have a list of arrays generated from another function:
testGroup = [array([18]), array([], dtype=int64), array([56, 75, 55, 55]), array([32])]
I'd like to return the sum of each individual array in the list, with the empty ones returning as zero
I've tried using numpy, as per the documentation:
np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
But when I try np.sum(testGroup, axis=1)
I get an axis error as I suppose the empty arrays have a dimension less than one?
I've also tried summing it directly arraySum = sum(testGroup)
but get a ValueError
Any ideas on how to achieve a sum of the arrays inside the
testGroup
list?
CodePudding user response:
testGroup
is a plain python list, that happens to contain numpy.array
elements. Instead you can use a list comprehension
>>> [np.sum(a) for a in testGroup]
[18, 0, 241, 32]
CodePudding user response:
Try
list(map(np.sum, testGroup))
it gives
[18, 0, 241, 32]
CodePudding user response:
You might use so-called list-comprehension to apply function to each element of list as follow
import numpy as np
testGroup = [np.array([18]), np.array([], dtype=np.int64), np.array([56, 75, 55, 55]), np.array([32])]
totals = [np.sum(i) for i in testGroup]
print(totals)
output
[18, 0, 241, 32]