Combining NumPy arrays

前端 未结 5 1324
北荒
北荒 2020-12-17 22:55

I have two 20x100x3 NumPy arrays which I want to combine into a 40 x 100 x 3 array, that is, just add more lines to the array. I am confused by which function I want: is it

5条回答
  •  旧时难觅i
    2020-12-17 22:59

    One of the best ways of learning is experimenting, but I would say you want np.vstack although there are other ways of doing the same thing:

    a = np.ones((20,100,3))
    b = np.vstack((a,a)) 
    
    print b.shape # (40,100,3)
    

    or

    b = np.concatenate((a,a),axis=0)
    

    EDIT

    Just as a note, on my machine for the sized arrays in the OP's question, I find that np.concatenate is about 2x faster than np.vstack

    In [172]: a = np.random.normal(size=(20,100,3))
    
    In [173]: c = np.random.normal(size=(20,100,3))
    
    In [174]: %timeit b = np.concatenate((a,c),axis=0)
    100000 loops, best of 3: 13.3 us per loop
    
    In [175]: %timeit b = np.vstack((a,c))
    10000 loops, best of 3: 26.1 us per loop
    

提交回复
热议问题