Simon Bergot
Simon Bergot

Reputation: 10582

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, axis=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']

Upvotes: 1

Views: 1516

Answers (1)

joris
joris

Reputation: 139142

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).

Upvotes: 2

Related Questions