user3468473
user3468473

Reputation: 21

How do I concatenate an array into a 3D matrix?

In my Python application I have a 3D matrix (array) such this:

array([[[ 1., 2., 3.]], [[ 4.,  5.,  6.]], [[ 7.,  8.,  9.]]])

and I would like to add, in a particular "line", for example, in the middle, zero arrays. At the end I would like to end with the following matrix:

array([[[ 1., 2., 3.]], [[ 4., 5., 6.]], [[ 0., 0., 0.]], [[ 0., 0., 0.]], [[ 7., 8., 9.]]])

Anybody knows how to solve this issue? I tried to use "numpy.concatenate", but it allow me only to add more "lines".

Thanks in advance!

Upvotes: 1

Views: 163

Answers (3)

Kei Minagawa
Kei Minagawa

Reputation: 4511

Possible duplicate of

Inserting a row at a specific location in a 2d array in numpy?

For example:

a = array([[[ 1., 2., 3.]], [[ 4.,  5.,  6.]], [[ 7.,  8.,  9.]]])
output = np.insert(a, 2, np.array([0,0,0]), 0)

output:

array([[[ 1.,  2.,  3.]],
       [[ 4.,  5.,  6.]],
       [[ 0.,  0.,  0.]],
       [[ 7.,  8.,  9.]]])

Why this works on 3D array?

See doc here. It says:

numpy.insert(arr, obj, values, axis=None)
...
Parameters :
    values : array_like
        Values to insert into arr.
        If the type of values is different from that of arr,
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        values is converted to the type of arr. values should be shaped so that
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        arr[...,obj,...] = values is legal.
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...

So it's very wise function!!

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249153

I'd do it this way:

>>> a = np.array([[[ 1., 2., 3.]], [[ 4.,  5.,  6.]], [[ 7.,  8.,  9.]]])

>>> np.concatenate((a[:2], np.tile(np.zeros_like(a[0]), (2,1,1)), a[2:]))
array([[[ 1.,  2.,  3.]],

       [[ 4.,  5.,  6.]],

       [[ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.]],

       [[ 7.,  8.,  9.]]])

The 2 in (2,1,1) given to tile() is how many zero "rows" to insert. The 2 in the slice indexes is of course where to insert.

If you're going to insert a large amount of zeros, it may be more efficient to just create a big array of zeros first and then copy in the parts you need from the original array.

Upvotes: 1

Bitwise
Bitwise

Reputation: 7805

Is this what you want?

result = np.r_[ a[:2], np.zeros(1,2,3), a[2][None] ]

Upvotes: 1

Related Questions