简体   繁体   中英

Append multiple 1D arrays to an “empty” 2D array - Python

Consinder the following example:

# z = empty object, if possible empty 2D-array
  N = 2

for i in range(N):
    l = i * array([2,2,2])
    # z.function(l)

Is there a function or a way to append multiple 1D-arrays to an empty object z and convert it into an 2D array

In my case N = 10**5 and the l-arrays are computed.

In the end i want a 2D array so i can apply slice operations (extract columns,rows,..)

You can just do

import numpy

x = numpy.array([1, 2, 3])

print(numpy.array([i*x for i in range(2)]))                                     

Output is:

array([[0, 0, 0],
       [1, 2, 3]])

If you are using Numpy library, you can do it with the following code:

    import numpy as np


    x = np.array([1,2,3]) 

    #making an empty array with the shape and data type used in x
    y = np.zeros(shape=x.shape,dtype=x.dtype) 

    #connecting two 1d arrays to a 2d one
    z = np.concatenate((y,x)) #joining 

    print(z)

this will connect them to:

   z= [[0, 0, 0],[1, 2, 3]]

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