Tarang
Tarang

Reputation: 75955

Numpy append vectors of same shape to different axis

I have a numpy array

import numpy as np

initial_array = np.array([[
        [0, 1],
        [1, 2],
        [2, 3],
        [3, 4]],

       [[4, 5],
        [5, 6],
        [6, 7],
        [7, 8]]])

I have an array I want to add in:

to_add = np.array([
       [ 8,  9],
       [ 9, 10],
       [10, 11],
       [11, 12]])

Here, initial_array has a shape of (2, 4, 2) and to_add has a shape of (4, 2). I'm looking for the final result with a shape (3, 4, 2):

result = np.array([[
        [ 0,  1],
        [ 1,  2],
        [ 2,  3],
        [ 3,  4]],

       [[ 4,  5],
        [ 5,  6],
        [ 6,  7],
        [ 7,  8]],

       [[ 8,  9],
        [ 9, 10],
        [10, 11],
        [11, 12]]])

How can this be done without converting the numpy array back to a python list, is it possible to do this using numpy alone?

Upvotes: 1

Views: 823

Answers (5)

daniboy000
daniboy000

Reputation: 1129

You can use numpy.append with to_add inside a list and appending only on the axis 0.

initial_array = np.array([[
        [0, 1],
        [1, 2],
        [2, 3],
        [3, 4]],

       [[4, 5],
        [5, 6],
        [6, 7],
        [7, 8]]])

to_add = np.array([
       [ 8,  9],
       [ 9, 10],
       [10, 11],
       [11, 12]])

final = np.append(initial_array, [to_add], axis=0)

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

A lot of ways actually, I'm showing a couple:

>>> result = np.insert(initial_array, initial_array.shape[0], to_add, axis=0)
# or
>>> result = np.vstack((initial_array,to_add[None,...]))
# or
>>> result = np.array([*initial_array, to_add])

Upvotes: 2

yatu
yatu

Reputation: 88246

You could just add an additional axis to to_add so they can be directly concatenated:

np.concatenate([initial_array, to_add[None,:]])

array([[[ 0,  1],
        [ 1,  2],
        [ 2,  3],
        [ 3,  4]],

       [[ 4,  5],
        [ 5,  6],
        [ 6,  7],
        [ 7,  8]],

       [[ 8,  9],
        [ 9, 10],
        [10, 11],
        [11, 12]]])

Upvotes: 1

Christian Sloper
Christian Sloper

Reputation: 7510

Without reshape:

np.concatenate((initial_array, [to_add]))

Upvotes: 1

Nicolas Gervais
Nicolas Gervais

Reputation: 36624

In addition to the other answers, you can also do that with np.newaxis():

np.concatenate([initial_array, to_add[np.newaxis, :]])

The result:

Out[75]: 
array([[[ 0,  1],
        [ 1,  2],
        [ 2,  3],
        [ 3,  4]],
       [[ 4,  5],
        [ 5,  6],
        [ 6,  7],
        [ 7,  8]],
       [[ 8,  9],
        [ 9, 10],
        [10, 11],
        [11, 12]]])

Upvotes: 1

Related Questions