2017-12-18 229 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