Skip to content Skip to sidebar Skip to footer

Numpy Append 3D Vectors Without Flattening

l have the following vector video_132.shape Out[64]: (64, 3) that l would to add to it a new 3D vector of three values video_146[1][146][45] such that video_146[1][146][45].shap

Solution 1:

For visual simplicity let's rename video_132 --> a, and video_146[1][146][45] --> b. The particular values aren't important so let's say

In [82]: a = np.zeros((64, 3))
In [83]: b = np.ones((3,))

Then we can append b to a using:

In [84]: np.concatenate([a, b[None, :]]).shape
Out[84]: (65, 3)

Since np.concatenate returns a new array, reassign its return value to a to "append" b to a:

a = np.concatenate([a, b[None, :]])

Solution 2:

Code for append:

def append(arr, values, axis=None):
    arr = asanyarray(arr)
    if axis is None:
        if arr.ndim != 1:
            arr = arr.ravel()
        values = ravel(values)
        axis = arr.ndim-1
    return concatenate((arr, values), axis=axis)

Note how arr is raveled if no axis is provided

In [57]: np.append(np.ones((2,3)),2)
Out[57]: array([1., 1., 1., 1., 1., 1., 2.])

append is really aimed as simple cases like adding a scalar to a 1d array:

In [58]: np.append(np.arange(3),6)
Out[58]: array([0, 1, 2, 6])

Otherwise the behavior is hard to predict.

concatenate is the base operation (builtin) and takes a list, not just two. So we can collect many arrays (or lists) in one list and do one concatenate at the end of a loop. And since it doesn't tweak the dimensions before hand, it forces us to do that ourselves.

So to add a shape (3,) to a (64,3) we have transform that (3,) into (1,3). append requires the same dimension adjustment as concatenate if we specify the axis.

In [68]: np.append(arr,b[None,:], axis=0).shape
Out[68]: (65, 3)
In [69]: np.concatenate([arr,b[None,:]], axis=0).shape
Out[69]: (65, 3)

Post a Comment for "Numpy Append 3D Vectors Without Flattening"