Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling np.sum(np.fromiter(generator))

Tags:

python

numpy

I have a generator that returns numpy arrays. For example sake, let it be:

import numpy as np
a = np.arange(9).reshape(3,3)
gen = (x for x in a)

Calling:

np.sum(gen)

On numpy 1.17.4:

DeprecationWarning: Calling np.sum(generator) is deprecated, and in the future will give a different result. Use np.sum(np.fromiter(generator)) or the python sum builtin instead.

Trying to refactor the above:

np.sum(np.fromiter(gen, dtype=np.ndarray))

I get:

ValueError: cannot create object arrays from iterator

What is wrong in the above statement?

like image 398
T81 Avatar asked Oct 26 '25 03:10

T81


2 Answers

The problem is the second argument, np.ndarray in the fromiter(). Numpy fromiter expected a 1D and returns a 1D array:

Create a new 1-dimensional array from an iterable object.

Therefore, you cannot create object arrays from iterator. Furthermore the .reshape() will also raise an error, because of what I stated in the first line. All in all, this works:

import numpy as np
a = np.arange(9)
gen = (x for x in a)
print(np.sum(np.fromiter(gen,float)))

Output:

36
like image 89
Celius Stingher Avatar answered Oct 28 '25 16:10

Celius Stingher


Since you're summing instances of arrays you can just use the built-in sum:

result = sum(gen)
like image 23
a_guest Avatar answered Oct 28 '25 17:10

a_guest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!