简体   繁体   中英

Faster way than numpy.less?

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM