Home > Blockchain >  how to work with loop and break statement over numpy ndarray
how to work with loop and break statement over numpy ndarray

Time:10-17

I have this data array of a :

>>>a
array([[1., 2., 3.],
      [4., 5., 6.]], dtype=float32)

Now I want to do something like this with the data:

>>>for n in range (1,4):
>>>    a  = 2
>>>    print(a)
[[3. 4. 5.]
 [6. 7. 8.]]
[[ 5.  6.  7.]
 [ 8.  9. 10.]]
[[ 7.  8.  9.]
 [10. 11. 12.]]

which will give me the final result of a:

>>> a
array([[ 7.,  8.,  9.],
       [10., 11., 12.]], dtype=float32)

if I want the iteration to stop for each element when the value is > 8, which likely would give me the final result like this:

>>> a
array([[7., 8., 7.],
      [8., 7., 8.]], dtype=float32)

how to do that?

thank you!

CodePudding user response:

One approach is:

import numpy as np

a = np.array([[1., 2., 3.],
              [4., 5., 6.]], dtype=np.float32)

for n in range(1, 4):
    a  = 2 * ((a   2) <= 8)

print(a)

Output

[[7. 8. 7.]
 [8. 7. 8.]]

The idea is to multiply 2 by a boolean mask that will be 1 if 2 can be added to the element of a else 0.

As an alternative, you could skip the for-loop altogether by doing the following:

a = 8 - (a % 2)
print(a)

Output

[[7. 8. 7.]
 [8. 7. 8.]]

The above solution is based on the fact that the numbers in a that are even will end up as 8 and odd numbers as 7, this is of course assuming that all the numbers in a are less than 8.

CodePudding user response:

Using np.where

Code

a = np.array([[1., 2., 3.],
      [4., 5., 6.]], dtype=np.float32)

for i in range(1, 4):
    a = np.where(a   2 <= 8, a 2, a)

Alternative (requires Python 3.8 )

You can use the Walrus operator to avoid computing a 2 twice:

for i in range(1, 4):
    a = np.where((p:=a   2) <= 8, p, a)

Output

print(a)
array([[7., 8., 7.],
       [8., 7., 8.]], dtype=float32)

Explanation

Syntax :numpy.where(condition[, x, y])
Parameters:
condition : When True, yield x, otherwise yield y.
  • Related