Append a numpy.array to a certain numpy.array stored in a list

前端 未结 2 1497
滥情空心
滥情空心 2021-01-28 05:45

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条回答
  • 2021-01-28 06:01

    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.

    0 讨论(0)
  • 2021-01-28 06:15

    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)
    
    0 讨论(0)
提交回复
热议问题