1

I would like to check a condition inside an array and perform an operation on the position where the condition is met. For example, this piece of code does the job:

res = somefunction(x)
for i in range(x.shape[0]):
    for j in range(x.shape[1]):
        if not 6 < res[i,j] < 18:
            x[i,j] = float('nan')

But I thought a faster (and shorter) way would maybe be something like this:

x[not 6 < somefunction(x) < 18] = float('nan')

But python gives the error that condition checking doesn't work in array with more than element. Is there a way to make my code go faster?

1
  • x[~((6 < x) & (x < 18))] = np.nan may work?
    – cs95
    Commented Dec 14, 2017 at 21:10

1 Answer 1

1

You can't use not or chained comparisons with arrays, since neither not nor chained comparisons can be implemented to broadcast.

Split the chained comparison into two comparisons, and use ~ and & instead of not and and, since NumPy uses the bitwise operators for boolean operations on boolean arrays:

x[~((6 < res) & (res < 18))] = numpy.nan
2
  • Okay, didn't see this when I posted. Will remove.
    – cs95
    Commented Dec 14, 2017 at 21:14
  • You should also include that x should either be float or object for this to work.
    – cs95
    Commented Dec 14, 2017 at 21:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.