0

I have the following problem. I want to extend a numpy array in a loop, so that each array is seperated from the next like a=[[1,2,3,4,5],[1,2,3,4,5]],b=[[1,2,3,4,5],[1,2,3,4,5]]-->[[[1,2,3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]]]

My approach so far:

count=0
for i in range(int(max(allCoo[:,4]))+1):

        mask1 = allCoo[:,4] == count 
        if count>0:
            trackList=np.vstack((trackList,np.array((allCoo[mask1]))))
        else:
            trackList=np.array((allCoo[mask1]))

        count+=1 

But this just give me things like: [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

Best regards

1
  • Collect the arrays in a list, or list of lists, and do the stack/concatenate once at the end. Commented Apr 21, 2017 at 10:10

1 Answer 1

2

You want to use dstack instead of vstack if you want a new dimension

p.dstack([a,b]).swapaxes(1,2)

array([[[1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5]],

       [[1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5]]])

np.vstack([a,b])

array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])
Sign up to request clarification or add additional context in comments.

3 Comments

Nice thank you. But what is for arrays with different array dumensions like np.dstack(([[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]]])).swapaxes(1,2). Here i get the error: ValueError: all the input array dimensions except for the concatenation axis must match exactly
That output would be a ragged array (since the second dimension would not be fixed) and thus wouldn't be a valid numpy array. You'd be better off making a list of arrays then.
np.stack is a newer function with more flexibility in adding that new dimension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.