Home > Net >  Faster way than numpy.less?
Faster way than numpy.less?

Time:04-23

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]

CodePudding user response:

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])
  • Related