Home > Net >  Concatenate arrays with stack numpy
Concatenate arrays with stack numpy

Time:02-10

import numpy as np

t = np.arange(3)

for i in range(5):
  a = np.arange(3)
  np.stack((t, a))

print(t)

output = [0 1 2]

Please some help to contatenate arrays in a loop for, ty!

CodePudding user response:

import numpy as np

t = np.arange(3)

for i in range(5):
  a = np.arange(3)
  t = np.vstack((t, a))

print(t)

Output:

[[0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]
 [0 1 2]]

CodePudding user response:

Note that avoidung for-loops makes the same task

  1. with nx,ny = 5,5 5 times faster
  2. with nx,ny = 50,50 31 times faster
  3. with nx,ny = 500,500 57 times faster

Here the code:

import numpy as np
nx = 500; ny = 500

def f0():
    t = np.arange(ny)
    for i in range(nx):
      a = np.arange(ny)
      t = np.vstack((t, a))   
    return t


def f1():
    o = np.ones(nx, dtype=int)
    t = np.arange(ny)
    return np.outer(o,t)  # the outer product between 2 vectors

%timeit y0 = f0()
13.2 ms ± 1.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


%timeit y1 = f1()
229 µs ± 1.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

CodePudding user response:

import numpy as np

t = np.arange(3)

for i in range(5):
  a = np.arange(3)
  t = np.concatenate((t, a))

print(t)

Output:

[0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2]
  • Related