# [Numpy-discussion] Offset 2D arrays

Mike Romberg romberg at fsl.noaa.gov
Wed Sep 19 11:50:02 CDT 2001

```>>>>> " " == Herbert L Roitblat <roitblat at hawaii.edu> writes:

> Konrad's solution is MUCH more elegant.

> Message ----- From: "Konrad Hinsen" <hinsen at cnrs-orleans.fr>
[snip]

>>
>> b = 0*a b[:-1, :-1] = a[1:, 1:]
>>

I think it looks cleaner as well.  I've managed to create a function
(with the help of the tips on this list) which can offset a 2d array
in either or both the x and y dimensions.  I strongly suspect that
someone who *gets* python and numeric slicing better than I, can come
up with a cleaner approach.

def getindicies(o, l):
if o > 0:
s1 = o; e1 = l; s2 = 0; e2 = l - o
elif o < 0:
s1 = 0; e1 = l + o; s2 = -o; e2 = l
else:
s1 = 0; e1 = l; s2 = 0; e2 = l
return s1, e1, s2, e2

# return a 2d array whose dimensions match a with the data offset
# controlled by x and y.
def offset(a, x, y):
sy1, ey1, sy2, ey2 = getindicies(y, a.shape[0])
sx1, ex1, sx2, ex2 = getindicies(x, a.shape[1])
b = zeros(a.shape)
b[sy1:ey1,sx1:ex1] = a[sy2:ey2,sx2:ex2]
return b

a = array(((1, 2, 3), (4, 5, 6), (7, 8, 9)))

# no offset
print offset(a, 0, 0)
# offset by 1 column in x
print offset(a, 1, 0)
# offset by 1 column (opposite dir) in x
print offset(a, -1, 0)
# offset by 2 columns in x
print offset(a, 2, 0)
# offset by 2 columns in y
print offset(a, 0, 2)

Thanks,

Mike Romberg (romberg at fsl.noaa.gov)

```