-1

i was think about if there is a faster way than the np.less functionality. Atm i'm comparing two arrays with np.less an get something like [true, true, false], after that im checking with a=np.where(x == True) to get the position of the true. After that im going through the list checking where values[a]. In my opinion there have to be a much faster way but i currently can't find on. Sorting the array is no option.

The code is is looking like this:

a = np.array([1, 2, 3])
b = np.array([2, 1, 8])
over = np.less(a, b)
# over = [True, False, True]
pos = np.where(over == True)[0]
# pos = [0, 2]
x = b[pos]
# x = [2,8]
Stay-Metal
  • 19
  • 6

1 Answers1

2

As Ali_Sh pointed out, just use the condition to fetch the values.

import numpy as np

a = np.array([1, 2, 3])
b = np.array([2, 1, 8])

b[np.less(a, b)]
# array([2, 8])
list(b[np.less(a, b)])  # for a list result instead of np arr
# [2, 8]

# or just
b[a < b]
# array([2, 8])

The issue is not the speed of np.less but the extra steps you've got. All of which are nearly-C-speed fast; just need to remove the unnecessary steps.

And even if you wanted to save the True/False results in over:

over = np.less(a, b)
b[over]
# array([2, 8])

over = a < b
b[over]
# array([2, 8])
aneroid
  • 12,983
  • 3
  • 36
  • 66
  • Note that `list(...)` on Numpy array should be avoided for sake of performance since it create a list of Numpy object (eg. `np.int32`) that are much more expensive than usual int. `.to_list()` should be used instead (see: https://stackoverflow.com/questions/69584027). Note that `np.less` has an `out` parameter so to avoid the relatively expensive array allocation (and some system overhead on big arrays like page-faults) assuming the preallocated array can be reused/recycled. – Jérôme Richard Apr 23 '22 at 13:53
  • @JérômeRichard, `list` is no longer used in this answer. And I don't see the use of `out` for a `b[a – hpaulj Apr 23 '22 at 16:34
  • @hpaulj I was referring to the `list(b[np.less(a, b)])` line in the answer. For the `out`, it may be a premature optimization, but you can do `b[np.less(a, b, buff)]` so to save a temporary array created (eg. in a loop). – Jérôme Richard Apr 23 '22 at 16:57
  • @JérômeRichard I added the `list` in `list(b[np.less(a, b)])` because it wasn't clear if the OP wanted an array or list output. For that use-case, buff wouldn't suffice. – aneroid Apr 24 '22 at 10:49