是否有更好的合并方式?
import numpy as np
def extract(a,indexes):
return a[indexes].T[indexes].T
def merge(a,indexes,b):
for i,ix in enumerate(indexes):
for j,jx in enumerate(indexes):
a[ix,jx] = b[i,j]
return a
N = 10
a = np.array(np.arange(N*N)).reshape(N,N)
indexes = [0,2,4,6,8]
b = extract(a,indexes)
print(a)
print(indexes)
print(b)
# make some changes in b
b=-b
res = merge(a,indexes,b)
https://docs.scipy.org/doc/numpy-1.10.0/user/basics.indexing.html#index-arrays
a:
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]]
indexes: [0, 2, 4, 6, 8]
b:
[[ 0 2 4 6 8]
[20 22 24 26 28]
[40 42 44 46 48]
[60 62 64 66 68]
[80 82 84 86 88]]
res: [[ 0, 1, -2, 3, -4, 5, -6, 7, -8, 9],
[ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[-20, 21, -22, 23, -24, 25, -26, 27, -28, 29],
[ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[-40, 41, -42, 43, -44, 45, -46, 47, -48, 49],
[ 50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[-60, 61, -62, 63, -64, 65, -66, 67, -68, 69],
[ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[-80, 81, -82, 83, -84, 85, -86, 87, -88, 89],
[ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
答案 0 :(得分:1)
您可以使用np.ix_
形成跨行和列的网格。因此,只需使用它索引输入数组并分配否定的b
值,如此 -
idx_grid = np.ix_(indexes, indexes)
a[idx_grid] = -b