# Numpy - adding a row to a 3d array

Chris Barker chrishbarker at home.net
Wed Aug 29 00:41:10 CEST 2001

Larry Whitley wrote:
> 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:
> 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

Sure you are. You want zeros() and concatenate():

>>> ar = arange( 24 )
>>> ar.shape = 2,3,4 # 2 planes, 3 rows, 4 columns
>>> concatenate((ar,zeros((2,1,4))),axis = 1)
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]]])

> My solution is pretty nasty.

It sure is!!

>I'm hoping some smart Pythonista can show me
> the light, the way, the truth, ... etc.  :-)

I don't know it it's the light, but I hope it helps!

-Chris

--
Christopher Barker,
Ph.D.
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------