4

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
1
  • 1
    This is just an example code and you actually do need iteration, not vectorization? If so, the "use vectorization" answers should be flagged. Commented Apr 16, 2019 at 20:45

4 Answers 4

9

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]])
Sign up to request clarification or add additional context in comments.

Comments

3

You may want to work on vectors and not loops?

In [144]: cakes = np.array([2, 3])

In [145]: cakes * 2 + 2
Out[145]: array([6, 8])

Comments

1

Your example doesn't work because ingredient isn't a mutable data type, it's an int or a float and an element within the larger structure -- you've got to modify the larger structure.

As it is though, the numpyonic way of doing this looks like:

ingredient = cakes * 2 + 2

The great advantage of numpy is its vectorized statements, like this one.

1 Comment

But is it possible to do it with an iteration rather than vectorized computing?
1

Use vectorization:

ingredient = cakes * 2 + 2

This will be much faster than dropping into python for loops, and the ability to do this is one of the major features offered by numpy. Vectorization allows numpy take advantage of the cpu cache, and use loops implemented in C. You'll want to get used to thinking in terms of operations like this to get the full power of numpy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.