numpy 循环通过NP阵列,每行长度不同

vhmi4jdf  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(189)

我有一个10行5列的np数组。我还有一个20行1列的数组。

a = [[15,2,1,0,0],
     [8,12,0,0,0],
     [4,12,10,9,0],
     [3,0,0,0,0],
     [19,7,0,0,0],
     [13,15,4,0,0],
     [0,0,0,0,0],
     [11,4,0,0,0],
     [7,0,0,0,0,0],
     [10,6,8,4,0]]


b =  [8,1,6,4,9,3,5,6,11,14,5,4,33,7,9,15,7,3,19,3]

对于数组a,一旦一行中的值为零,之后的任何值都将为零。
我想循环遍历a中的每一行,找到B中的第n个值,然后将其存储在一个名为c的10 x5数组中。
例如,c中的前两行将是:

[[9,1,8,0,0],
 [6,4,0,0,0]]

谢谢大家!

b1zrtrql

b1zrtrql1#

您可以使用索引:

# output with the shape of a
c = np.zeros_like(a)

# non-zero positions
m = a != 0

# assign values
c[m] = b[a[m]-1]

numpy.where更短的替代方案(但如果有很多零,效率可能会降低):

c = np.where(a!=0, b[a-1], 0)

输出:

array([[ 9,  1,  8,  0,  0],
       [ 6,  4,  0,  0,  0],
       [ 4,  4, 14, 11,  0],
       [ 6,  0,  0,  0,  0],
       [19,  5,  0,  0,  0],
       [33,  9,  4,  0,  0],
       [ 0,  0,  0,  0,  0],
       [ 5,  4,  0,  0,  0],
       [ 5,  0,  0,  0,  0],
       [14,  3,  6,  4,  0]])

可重现输入:

a = np.array([[15,  2,  1,  0,  0],
              [ 8, 12,  0,  0,  0],
              [ 4, 12, 10,  9,  0],
              [ 3,  0,  0,  0,  0],
              [19,  7,  0,  0,  0],
              [13, 15,  4,  0,  0],
              [ 0,  0,  0,  0,  0],
              [11,  4,  0,  0,  0],
              [ 7,  0,  0,  0,  0],
              [10,  6,  8,  4,  0]])

b =  np.array([ 8,  1,  6,  4,  9,  3,  5,  6, 11, 14,  5,  4, 33,  7,  9, 15,  7,
                3, 19,  3])
计时

在(10000,5)上,大部分为非零

# indexing
203 µs ± 6 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

# numpy.where
97.2 µs ± 2.02 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

On(10000,10005),只有前5列为非零

# indexing
2.2 s ± 384 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# numpy.where
4.73 s ± 680 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

相关问题