2017-12-18 248 views
1

我想将一个块从一个矩阵复制到另一个矩阵中。 要使用任何类型的n维数组,我需要通过[]运算符应用带有偏移量的列表。有没有办法做到这一点?Python:使用列表来索引[from:to]任意numpy数组

mat_bigger[0:5, 0:5, ..] = mat_smaller[2:7, 2:7, ..] 

,如:

off_min = [0,0,0] 
off_max = [2,2,2] 
for i in range(len(off_min)): 
    mat_bigger[off_min[i] : off_max[i], ..] = .. 
+0

是我使用numpy的 – dgrat

+0

选中此https://stackoverflow.com/questions/26506204/replace-sub-part-of-matrix-by-another-small-matrix-in-numpy – AndreyF

+0

或[this](https://stackoverflow.com/a/47605511/7207392) –

回答

2

您可以通过创建slice一组对象做到这一点。例如:

mat_big = np.zeros((4, 5, 6)) 
mat_small = np.random.rand(2, 2, 2) 

off_min = [2, 3, 4] 
off_max = [4, 5, 6] 

slices = tuple(slice(start, end) for start, end in zip(off_min, off_max)) 

mat_big[slices] = mat_small