Home > Software design >  Adding a row vector to a 3-D numpy array
Adding a row vector to a 3-D numpy array

Time:10-30

Suppose I have a 3-D array in numpy

a = [ [[1,2], [3,4]] , [[5,6], [7,8]] ]

I want to add a new row vector to a matrix so that the output would be for example, if I wanted to add the row vector [9,10] to the second matrix in the 3d array:

a = [ [[1,2], [3,4]] , [[5,6], [7,8], [9,10]] ]

I know how to add row vectors to 2-D arrays using np.append. But I don't know how to do it with 3-D arrays. I have tried to use np.append but all I get are either dimension errors, flattened arrays or just the wrong array. What would be the correct way to do this in numpy?

CodePudding user response:

You can achieve you goal like as follows, but the question remains in how far this is sensible because vectorization with an array that has dtype=object becomes more difficult. But here you go:

import numpy as np
a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8]] ])
b = np.array([9,10])

res = np.array([a[0],np.vstack([a[1],b])],dtype=object)

Output:

array([array([[1, 2],
              [3, 4]]), array([[ 5,  6],
                               [ 7,  8],
                               [ 9, 10]])], dtype=object)

CodePudding user response:

Numpy does memory optimization and creates np.ndarray of the size that you requested. It's better that you create an array of the size that you need at once and manipulate it instead of adding new rows many times.

So, if you will use many appends: use list. If you know the total size: use numpy array.

Another problem that you face is: The shape is not uniform. That is

a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8]] ])
# a.shape is (2, 2, 2)
new_a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8], [9, 10] ])
# What is the shape of new_a?

A code that does what you want is:

import numpy as np
a = np.array([ [[1,2], [3,4]] , [[5,6], [7,8]] ])
b = np.array([9,10])


res = np.zeros(a.shape[0], dtype="object")
res[0] = a[0]
res[1] = np.zeros((a.shape[1] 1, a.shape[2]))
res[1, :-1] = a[1, :]
res[1, -1] = b
  • Related