简体   繁体   中英

Appending 2-D numpy array to 3-D numpy array

I have a loop that creates a new (2, 3) array every time. I want to append these arrays together to create a new array 3-D array, I think an example explains what I want to do best. Say I have an array arr1 = array([[1, 2, 3], [4, 5, 6]]) and an array arr2 = array([[11, 22, 33], [44, 55, 66]]) . I want to get a new array by "adding the arrays" so something like arr3 = np.array([[[1, 11], [2, 22], [3, 33]], [[4,44], [5,55], [6,66]]]) . In practice this would look something like:

import numpy as np

n_samples = 10
total_arr = np.empty([2, 3, n_samples])

for i in range(n_samples):
   arr = np.random.rand(2,3)
   total_arr.append(arr) #This is the step I don't know what do do with

print(total_arr.shape)
>>> (2, 3, 10) #Where 10 is whatever n_samples is

My current method is to cast total_arr to a list with total_lst = total_arr.tolist() and append each arr[i,j] to the lists in total_lst with a for loop. So something like total_list[i][j].append(arr[i,j]) but this is taking much too long, is there a numpy solution for this?

Thanks

In [179]: arr1 = np.array([[1, 2, 3], [4, 5, 6]]); arr2 = np.array([[11, 22, 33], [44, 55, 66]])                
In [180]: arr1                                                                                                  
Out[180]: 
array([[1, 2, 3],
       [4, 5, 6]])
In [181]: arr2                                                                                                  
Out[181]: 
array([[11, 22, 33],
       [44, 55, 66]])

np.stack can join a list of arrays along a new axis. The default is to act like np.array([arr1, arr2]) , but it looks like you want a new last axis:

In [182]: np.stack([arr1, arr2], axis=2)                                                                        
Out[182]: 
array([[[ 1, 11],
        [ 2, 22],
        [ 3, 33]],

       [[ 4, 44],
        [ 5, 55],
        [ 6, 66]]])

In general, collecting the arrays in a list and doing one 'join' at the end is best. Trying to the array join iterative is slower, and harder to do right.

Alternatively you can create an array of the right target size, and assign elements/blocks.

===

New first axis example:

In [183]: np.stack([arr1, arr2])                                                                                
Out[183]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[11, 22, 33],
        [44, 55, 66]]])
In [184]: np.stack([arr1, arr2]).transpose(1,2,0)                                                               
Out[184]: 
array([[[ 1, 11],
        [ 2, 22],
        [ 3, 33]],

       [[ 4, 44],
        [ 5, 55],
        [ 6, 66]]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM