Numpy - adding a row to a 3d array

Larry Whitley ldw at us.ibm.com
Tue Aug 28 17:42:45 EDT 2001


I'm writing some code where I need to add a row to the end of each plane in
a 3d array.  The new row will end up with all zeros, the data in the old
rows should remain as is.  My first thought was Numpy's resize function but:

>>> ar = arange( 24 )
>>> ar.shape = 2,3,4 # 2 planes, 3 rows, 4 columns
>>> ar
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> newShape = ar.shape
>>> newShape[1] += 1 # add a row
>>> newShape
2,4,4
>>> ar = resize( ar, newShape )
>>> ar
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15]],
       [[16, 17, 18, 19],
        [20, 21, 22, 23],
        [ 0,  1,  2,  3],
        [ 4,  5,  6,  7]]])

Yuk.  The size is right but the data is in the wrong places.

What I want is:
>>> ar
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [ 0,0,0,0]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23],
        [0,0,0,0]]])

I understand that I'm not likely to get the zeros assigned in one fell swoop
but I would like the data in the old rows of the original array perserved.
My solution is pretty nasty.  I'm hoping some smart Pythonista can show me
the light, the way, the truth, ... etc.  :-)

    def _addRow(self, ar3 ): # ar3 is a reference
        # adds a row to a 3d array, keeping original data in the right place
        shape = ar3.shape
        # break the 3d array down into a list of 2d arrays and add a row to
each
        ar2List = []
        for i in range( shape[0] ):
            ar2 = ar3[i,:,:].copy() # make a copy of this plane
            newShape = ar2.shape
            newShape[0] += 1
            ar2 = resize( ar2, newShape ) # add a row
            ar2[-1,:] = 0 # zero the new row out
            ar2List.append( ar2 )
        # resize ar3
        shape[1] += 1
        ar3 = resize( ar3, shape ) # add a row, data is hosed
        # now fixup the data from the ar2List
        for i in range( len(ar2List)):
            ar3[i,:,:] = ar2

Larry








More information about the Python-list mailing list