计算numpy列表中项目的确切共同出现次数

Zen*_*nie 3 python numpy

我试图找出最快的方法来计算两个值在numpy列表中一个接一个地定位的时间.

例如:

list = [1, 5, 4, 1, 2, 4, 6, 7, 2, 1, 3, 3, 1, 2] 我想计算值1跟随值的次数2(但反之亦然)

在上面的例子中,答案应该是1因为1如下2只有一次.

我显然可以通过一个简单的for循环来达到答案,每次项目i相等1且item i-1等于时2,它会添加到计数器中,但我觉得必须有更快的方法来做到这一点,

谢谢

sac*_*cuL 5

你可以使用np.diff和做这个np.where:

import numpy as np

mylist = [1, 5, 4, 1, 2, 4, 6, 7, 2, 1, 3, 3, 1, 2]

# Turn your list into a numpy array
myarray = np.array(mylist)

# find occurences where myarray is 2 and the following element is 2 minus 1
np.sum((myarray[:-1] == 2) & (np.diff(myarray) == -1))
Run Code Online (Sandbox Code Playgroud)

哪个回报 1

大阵列上的时间:

在一个小的列表中,迭代方法和numpy方法之间的时间差异将不明显.但是在大型阵列上,如下例所示,性能numpy要好得多.

import timeit

mylist = np.random.choice(range(0,9), 1000000)

def np_method(mylist = mylist):
    return np.sum((mylist[:-1] == 2) & (np.diff(mylist) == -1))

def zip_loop(a = mylist):
    return len( [1 for i,j in zip(a, a[1:]) if i == 2 and j == 1] )

def for_loop(list1 = mylist):
    count=0
    desired_num=2
    follower_num=1
    for i in range(len(list1)-1):
        if list1[i]==desired_num:
            if list1[i+1]==follower_num:
                count+=1
    return count

>>> timeit.timeit(np_method, number = 100) / 100
0.006748438189970329

>>> timeit.timeit(zip_loop, number = 100) / 100
0.3811768989200209

>>> timeit.timeit(for_loop, number = 100) / 100
0.3774999916599336
Run Code Online (Sandbox Code Playgroud)