Home > Software engineering >  How to add numpy array variables by index without using loops
How to add numpy array variables by index without using loops

Time:08-05

I have this problem where I would prefer not using loops because I am working with a big data as a solution :

This is what I am trying to do : (I know this works to [6 6 6], but I want to "join" it by index)

import numpy as np

np_1 = np.asarray([1,1,1])
np_2 = np.asarray([2,2,2])
np_3 = np.asarray([3,3,3])

np_4 = np_1   np_2   np_3
# np_4 should be [1,2,3,1,2,3,1,2,3]

Are there ways to do this? or should I look for options outside of numpy?

CodePudding user response:

Try this:

np.array([np_1, np_2, np_3]).transpose().flatten()

CodePudding user response:

You can try the following method:

np.ravel(np.stack(np_1,np_2,np3),'F')

CodePudding user response:

One way to do it is to stack the sequences depth-wise and flatten it:

np.dstack([np_1, np_2, np_3]).flatten()
  • Related