Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

python - How to "embed" a small numpy array into a predefined block of a large numpy array?

I have a small NXN array "block" that I want to plug into a specified region (i.e., a diagonal region at "start") of a large array "wall". Is there an efficient method to archive this?

wall[start:start+N][start:start+N] = block[:][:]

currently what I am doing is simply:

for i in xrange(N):
    wall[start+i][start:start+N] = block[i][:]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use multi dimension index:

import numpy as np

wall = np.zeros((10,10),dtype=np.int)
block = np.arange(1,7).reshape(2,3)

x = 2
y = 3
wall[x:x+block.shape[0], y:y+block.shape[1]] = block

the output is:

>>> wall
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 2, 3, 0, 0, 0, 0],
       [0, 0, 0, 4, 5, 6, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...