Skip to content Skip to sidebar Skip to footer

Append A Numpy.array To A Certain Numpy.array Stored In A List

I have been for hours strugling to understand why i am not able to do this: >>> import numpy as np >>> a = [np.empty((0,78,3)) for i in range(2)] >>> b

Solution 1:

Stay away from np.append. Learn to use np.concatenate correctly. This append just creates confusion.

Given your definitions, this works:

In [20]: a1 = [np.concatenate((i,b),axis=0) for i in a]
In [21]: [i.shape for i in a1]
Out[21]: [(1, 78, 3), (1, 78, 3)]
In [22]: a
Out[22]: 
[array([], shape=(0, 78, 3), dtype=float64),
 array([], shape=(0, 78, 3), dtype=float64)]
In [23]: b.shape
Out[23]: (1, 78, 3)
In [24]: a1 = [np.concatenate((i,b),axis=0) for i in a]
In [25]: [i.shape for i in a1]
Out[25]: [(1, 78, 3), (1, 78, 3)]

A (0,78,3) can concatenate on axis 0 with a (1,78,3) array, producing another (1,78,3) array.

But why do it? It just makes a list with 2 copies of b.

c = [b,b]

does that just as well, and is simpler.

If you must collect many arrays of shape (78,3), do

alist = []
for _ in range(n):
   alist.append(np.ones((78,3)))

The resulting list of n arrays can be turned into an array with

np.array(alist)   # (n, 78, 3) array

Or if you collect a list of (1,78,3) arrays, np.concatenate(alist, axis=0) will join them into the (n,78,3) array.

Solution 2:

Your're not appending b but [b]. That doesn't work.

So in order to append b, use

a[0] = np.append(a[0],b,axis=0)

Post a Comment for "Append A Numpy.array To A Certain Numpy.array Stored In A List"