0

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].shape
Out[68]: (3,)

and

video_146[1][146][45]
Out[69]: array([217, 207, 198], dtype=uint8)

when l do the following

np.append(video_132,video_146[1][146][45])

l'm supposed to get

video_132.shape
Out[64]: (65, 3) # originally (64,3)

However l get :

Out[67]: (195,) # 64*3+3=195

It seems that it flattens the vector

How can l do the append by preserving the 3D structure ?

Joseph
  • 343
  • 6
  • 18
  • look at the code for !append`. It flattens the inputs when you don't specify an axis. It confuses too many users. Avoid it. – hpaulj Feb 21 '18 at 19:30

2 Answers2

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, :]])
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

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)
hpaulj
  • 221,503
  • 14
  • 230
  • 353