python – numpy获取行和列索引2D数组的所有组合

我有一个2D numpy数组如下:

import numpy as np
foo = np.array([[(i+1)*(j+1) for i in range(10)] for j in range(5)])

    #array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
    #       [ 2,  4,  6,  8, 10, 12, 14, 16, 18, 20],
    #       [ 3,  6,  9, 12, 15, 18, 21, 24, 27, 30],
    #       [ 4,  8, 12, 16, 20, 24, 28, 32, 36, 40],
    #       [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]])

我使用np.nonzero创建了一些过滤条件:

csum = np.sum(foo,axis=0)
#array([ 15,  30,  45,  60,  75,  90, 105, 120, 135, 150])
rsum = np.sum(foo,axis=1)
#array([ 55, 110, 165, 220, 275])
cfilter = np.nonzero(csum > 80)
#(array([5, 6, 7, 8, 9]),)
rfilter = np.nonzero(rsum < 165)
#(array([0, 1]),)

现在是否有一些优雅的numpy切片方法来获得rfilter中的r和cfilter中的r的所有foo [r,c]组合?即我想获得以下输出:

array([[ 6,  7,  8,  9, 10],
       [12, 14, 16, 18, 20]])

注意:我知道很容易进行基本切片选择以从数组中获取块,但在更高级的用例中,cfilter和rfilter中的索引不一定紧挨着彼此.

非常感谢!

最佳答案
另一种方法是使用索引两次:

In [167]: foo[rsum<165][:,csum>80]
Out[167]: 
array([[ 6,  7,  8,  9, 10],
       [12, 14, 16, 18, 20]])

它可读且相当快:

In [168]: %timeit foo[rsum<165][:,csum>80]
100000 loops, best of 3: 9.66 us per loop

In [170]: %timeit foo[np.ix_(rsum<165, csum>80)]
100000 loops, best of 3: 16.4 us per loop

PS:创建foo的更快的方法是

In [31]: np.multiply.outer(range(1,6),range(1,11))
Out[31]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
       [ 2,  4,  6,  8, 10, 12, 14, 16, 18, 20],
       [ 3,  6,  9, 12, 15, 18, 21, 24, 27, 30],
       [ 4,  8, 12, 16, 20, 24, 28, 32, 36, 40],
       [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]])

In [32]: %timeit np.multiply.outer(range(1,6),range(1,11))
100000 loops, best of 3: 14.2 us per loop

In [33]: %timeit np.array([[(i+1)*(j+1) for i in range(10)] for j in range(5)])
10000 loops, best of 3: 26.6 us per loop

转载注明原文:python – numpy获取行和列索引2D数组的所有组合 - 代码日志