Element-wise broadcasting for comparing two NumPy arrays?

后端 未结 3 809
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 04:54

Let\'s say I have an array like this:

import numpy as np

base_array = np.array([-13, -9, -11, -3, -3, -4,   2,  2,
                         2,  5,   7,  7,          


        
3条回答
  •  旧巷少年郎
    2021-01-19 05:36

    Here's one with np.searchsorted with focus on memory efficiency and hence performance -

    def get_comparative_sum(base_array, comparison_array):
        n = len(base_array)
        base_array_sorted = np.sort(base_array)
        idx = np.searchsorted(base_array_sorted, comparison_array, 'right')
        idx[idx==n] = n-1
        return n - idx - (base_array_sorted[idx] == comparison_array)
    

    Timings -

    In [40]: np.random.seed(0)
        ...: base_array = np.random.randint(-1000,1000,(10000))
        ...: comparison_array = np.random.randint(-1000,1000,(20000))
    
    # @miradulo's soln
    In [41]: %timeit np.sum(comparison_array[:, None] < base_array, axis=1)
    1 loop, best of 3: 386 ms per loop
    
    In [42]: %timeit get_comparative_sum(base_array, comparison_array)
    100 loops, best of 3: 2.36 ms per loop
    

提交回复
热议问题