Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate and modify array with NumPy

I have two vectors x and y with same length defined with NumPy.

How can I iterate through x and modify values in y?

I mean something like

ingredients = empty(cakes.shape)
for ingredient, cake in np.nditer([ingredients,cakes]):
    ingredient = cake * 2 + 2
like image 731
Jamgreen Avatar asked Oct 20 '25 21:10

Jamgreen


1 Answers

As others have said, using vectorization is typically better/faster/nicer/...

But if you have good reasons to use iteration, you can of course do it.

I just copied this from the official documentation:

>>> a = np.arange(6).reshape(2,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> for x in np.nditer(a, op_flags=['readwrite']):
...     x[...] = 2 * x
...
>>> a
array([[ 0,  2,  4],
       [ 6,  8, 10]])
like image 88
Matthias Avatar answered Oct 22 '25 12:10

Matthias



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!