Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 给定索引列表的数组上的部分和_Python_Arrays_Performance_Numpy_Multidimensional Array - Fatal编程技术网

Python 给定索引列表的数组上的部分和

Python 给定索引列表的数组上的部分和,python,arrays,performance,numpy,multidimensional-array,Python,Arrays,Performance,Numpy,Multidimensional Array,我有一个2D矩阵,我需要求矩阵元素的一个子集的和,给定两个索引列表imp\u list和bath\u list。以下是我现在正在做的事情: s = 0.0 for i in imp_list: for j in bath_list: s += K[i,j] 看起来很慢。执行求和的更好解决方案是什么?如果您使用的是大型数组,那么与Python的for循环相比,使用NumPy自己的索引例程应该可以大大提高速度 在一般情况下,您可以使用np.ix选择要求和的矩阵子数组: K[

我有一个2D矩阵,我需要求矩阵元素的一个子集的和,给定两个索引列表
imp\u list
bath\u list
。以下是我现在正在做的事情:

s = 0.0
for i in imp_list:
    for j in bath_list:
        s += K[i,j]

看起来很慢。执行求和的更好解决方案是什么?

如果您使用的是大型数组,那么与Python的
for
循环相比,使用NumPy自己的索引例程应该可以大大提高速度

在一般情况下,您可以使用
np.ix
选择要求和的矩阵子数组:

K[np.ix_(imp_list, bath_list)].sum()
请注意,
np.ix
会带来一些开销,因此,如果两个列表包含连续或等距的值,则值得使用常规切片来索引数组(请参见下面的
method3()

以下是一些数据来说明改进:

K = np.arange(1000000).reshape(1000, 1000)
imp_list = range(100)  # [0, 1, 2, ..., 99]
bath_list = range(200) # [0, 1, 2, ..., 199]

def method1():
    s = 0
    for i in imp_list:
        for j in bath_list:
            s += K[i,j]
    return s

def method2():
    return K[np.ix_(imp_list, bath_list)].sum()

def method3():
    return K[:100, :200].sum()
然后:


它很慢,因为它是一个n^2算法。事实就是这样。你必须以这样或那样的方式访问所有这些位置。imp_列表有多大,bath_列表有多大?在这里使用numpy非常有用。这是链接谢谢,完全符合我的需要,它节省了我很多时间,我还可以在其他函数中重复使用你的方法。
In [80]: method1() == method2() == method3()
Out[80]: True

In [91]: %timeit method1()
10 loops, best of 3: 9.93 ms per loop

In [92]: %timeit method2()
1000 loops, best of 3: 884 µs per loop

In [93]: %timeit method3()
10000 loops, best of 3: 34 µs per loop