简体   繁体   中英

Concatenate arrays with stack numpy

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!

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]]

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)
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]

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