[Numpy-discussion] copying array to itself

Henry Gomersall heng at cantab.net
Wed May 2 12:03:04 EDT 2012

I'm need to do some shifting of data within an array and am using the
following code:

for p in numpy.arange(array.shape[0], dtype='int64'):
    for q in numpy.arange(array.shape[1]):
        # A positive shift is towards zero            
        shift = shift_values[p, q]

        if shift >= 0:
            copy_len = array.shape[2] - shift
            array[p, q, :copy_len] = array[p, q, shift:]
            array[p, q, copy_len:] = 0

            neg_shift = -shift
            copy_len = array.shape[2] - neg_shift
            array[p, q, neg_shift:] = array[p, q, :copy_len]
            array[p, q, :neg_shift] = 0

In essence, if shift is positive, it copies the data to a block closer
the zero index on the last dimension, and if its negative, it copies it
to a block further away.

The problem I've encountered is that in for some values of p and q
(which is consistent), it simply writes deterministic and consistent
garbage (a repeated pattern around around -0.002) to that last dimension
to which I'm trying to copy. Most of the values of p and q work fine and
as expected. I can solve the problem with an interim copy.

Is this some nuance of the way numpy does things? Or am I missing some
stupid bug in my code?



More information about the NumPy-Discussion mailing list