numpy:在排序列表中,找到每个唯一值的第一个和最后一个索引

时间:2017-11-26 11:16:08

标签: python numpy

有一个排序列表,如何找到(使用numpy)每个唯一值的第一个和最后一个索引?

示例:

初始排序列表:

UPDATE campaigns
SET campaign_id= (select id order by id desc LIMIT 1)
WHERE id = (select id order by id desc LIMIT 1)

结果如下:

首先:[0,0,0,3,3,5,6,6,6]

最后:[2,2,2,4,4,5,8,8,8]

提前谢谢

2 个答案:

答案 0 :(得分:3)

这是一种利用输入数据的排序特性的方法,利用非常有效的NumPy array-slicing和其他NumPy函数 -

def start_stop_arr(initial_list):
    a = np.asarray(initial_list)
    mask = np.concatenate(([True], a[1:] != a[:-1], [True]))
    idx = np.flatnonzero(mask)
    l = np.diff(idx)
    start = np.repeat(idx[:-1], l)
    stop = np.repeat(idx[1:]-1, l)
    return start, stop

连续重复可以进一步提升性能 -

def start_stop_arr_concat_repeat(initial_list):
    a = np.asarray(initial_list)
    mask = np.concatenate(([True], a[1:] != a[:-1], [True]))
    idx = np.flatnonzero(mask)
    l = np.diff(idx)
    idx2 = np.concatenate((idx[:-1,None], (idx[1:,None]-1)),axis=1)
    ss = np.repeat(idx2, l, axis=0)
    return ss[:,0], ss[:,1]

示例运行 -

In [38]: initial_list
Out[38]: array([0, 0, 0, 1, 1, 2, 3, 3, 3])

In [39]: start_stop_arr(initial_list)
Out[39]: (array([0, 0, 0, 3, 3, 5, 6, 6, 6]), array([2, 2, 2, 4, 4, 5, 8, 8, 8]))

运行时测试 -

其他方法 -

# @Mohammed Elmahgiubi's soln
def reversed_app(initial_list): # input expected is a list
    reversed_initial_list = list(reversed(initial_list))
    first = [initial_list.index(i) for i in initial_list]
    last = list(reversed([(len(initial_list) - 
                           (reversed_initial_list.index(i) + 1)) 
                            for i in reversed_initial_list]))
    return first, last

def unique_app(a): # @B. M.'s soln
    _,ind1,inv1,cou1 = np.unique(a, return_index=True, return_inverse=True, 
                                 return_counts=True)
    return ind1[inv1],(ind1+cou1-1)[inv1]

计时 -

案例#1:较小的数据集

In [295]: initial_list = np.random.randint(0,1000,(10000))
     ...: initial_list.sort()

In [296]: input_list = initial_list.tolist()

In [297]: %timeit reversed_app(input_list)
1 loop, best of 3: 789 ms per loop

In [298]: %timeit unique_app(initial_list)
1000 loops, best of 3: 353 µs per loop

In [299]: %timeit start_stop_arr(initial_list)
10000 loops, best of 3: 96.3 µs per loop

案例#2:更大的数据集

In [438]: initial_list = np.random.randint(0,100000,(1000000))
     ...: initial_list.sort()

In [439]: %timeit unique_app(initial_list) # @B. M.'s soln
10 loops, best of 3: 53 ms per loop

In [440]: %timeit start_stop_arr(initial_list)
100 loops, best of 3: 9.64 ms per loop

In [441]: %timeit start_stop_arr_concat_repeat(initial_list)
100 loops, best of 3: 6.76 ms per loop

答案 1 :(得分:0)

numpy.unique计算所有有用的值:

a=np.array([0, 0, 0, 1, 1, 2, 3, 3, 3])
_,ind1,inv1,cou1 = np.unique(a, return_index=True, return_inverse=True, return_counts=True)

print(ind1[inv1],(ind1+cou1-1)[inv1])

#[0 0 0 3 3 5 6 6 6] [2 2 2 4 4 5 8 8 8]