开发者

replicating borders in 2d numpy arrays

I am trying to replicate the border of a 2d numpy array:

>>> from numpy import *
>>> test = array(range(9)).reshape(3,3)
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

Is there an easy way to replicate a border in any direction?

for example:

>>>> replicate(test, idx=0, 开发者_如何学Goaxis=0, n=3) 
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

edit:

the following function did the job:

def replicate(a, xy, se, n):
    rptIdx = numpy.ones(a.shape[0 if xy == 'X' else 1], dtype=int)
    rptIdx[0 if se == 'start' else -1] = n + 1
    return numpy.repeat(a, rptIdx, axis=0 if xy == 'X' else 1)

with xy in ['X', 'Y'] and se in ['start', 'end']


You can use np.repeat:

In [5]: np.repeat(test, [4, 1, 1], axis=0)
Out[5]: 
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

But for larger/variable arrays it will be more difficult to define the repeats argument ([4, 1, 1], which is in this case how many times you want to repeat each row).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜