Home > Software design >  Appending multiple arrays into a single array in Python
Appending multiple arrays into a single array in Python

Time:06-21

I want to append starting from B1[0,0] to B1[0,6] into a single array B with shape (1,7,2). The desired output is attached.

import numpy as np

B1[0,0]=np.array([0,1])
B1[0,1]=np.array([1,3])
B1[0,2]=np.array([2,5])
B1[0,3]=np.array([3,4])
B1[0,4]=np.array([4,7])
B1[0,5]=np.array([5,6])
B1[0,6]=np.array([6,7])

The desired output is

B = np.array([[[0, 1],
        [1, 3],
        [2, 5],
        [3, 4],
        [4, 7],
        [5, 6],
        [6, 7]]])

CodePudding user response:

Starting with a correct B1 array, you assignment does what you want:

In [211]: B1 = np.zeros((1,7,2),int)

In [212]: B1
Out[212]: 
array([[[0, 0],
        [0, 0],
        [0, 0],
        [0, 0],
        [0, 0],
        [0, 0],
        [0, 0]]])

In [213]: B1[0,0]=np.array([0,1])
     ...: B1[0,1]=np.array([1,3])
     ...: B1[0,2]=np.array([2,5])
     ...: B1[0,3]=np.array([3,4])
     ...: B1[0,4]=np.array([4,7])
     ...: B1[0,5]=np.array([5,6])
     ...: B1[0,6]=np.array([6,7])

In [214]: B1
Out[214]: 
array([[[0, 1],
        [1, 3],
        [2, 5],
        [3, 4],
        [4, 7],
        [5, 6],
        [6, 7]]])

What's your problem?

If instead you start with a list of such arrays, you can easily "unite' them with np.array:

In [217]: alist = list(B1[0])

In [218]: alist
Out[218]: 
[array([0, 1]),
 array([1, 3]),
 array([2, 5]),
 array([3, 4]),
 array([4, 7]),
 array([5, 6]),
 array([6, 7])]

In [219]: np.array(alist)
Out[219]: 
array([[0, 1],
       [1, 3],
       [2, 5],
       [3, 4],
       [4, 7],
       [5, 6],
       [6, 7]])
  • Related