﻿ python – numpy获取行和列索引2D数组的所有组合 - 代码日志

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

``````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]])
``````

``````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]),)
``````

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

``````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
``````