2

I would like to fill a 3D numpy array which has dimension (?, 100, 100). The first dimension will range between 500 and 1000 but is not known beforehand. I could use the append method, but this is slow.

Is there another posibility to create such a 3D numpy array where the first dimension is not known beforehand? The numpy array is filled using a for loop.

Second, let's assume I have the following two numpy arrays:

import numpy as np
arr1 = np.random.randint(0, 100, size=(30, 100, 100))
arr2 = np.random.randint(0, 100, size=(50, 100, 100))

How can I concatenate arr1 and arr2 along the first dimension so that the resulting array has shape (80, 100, 100)?

4
  • 1
    np.concatenate((arr1, arr2), axis=0) Commented Jul 15, 2019 at 22:53
  • If you need to define the component arrays in a loop, collect them in a list, with list.append. Then do one concatenate (or maybe vstack or stack) at the end. Commented Jul 16, 2019 at 1:16
  • @hpaulj I have collected the arrays in a list, i.e. I have a list containing 2D arrays. When I use vstack or stack or concatenate over the list, then the arrays are concatenated either on the first or second dimension which I don't want. What I want is that when arrays in list have dimensions (a,b), I would like to get a resulting arrays with dimensions (n,a,b). Is this possible? Commented Jul 16, 2019 at 9:22
  • np.stack uses a new dimension. Commented Jul 16, 2019 at 11:07

1 Answer 1

2

About the first question, I always use np.empty and np.append methodes which are totaly fine.

arr = np.empty((0, 100, 100), int)
arr = np.append(arr,x,axis=0)

about the second question, append works well again:

arr3  = np.append(arr1, arr2, axis=0)

also 'concatenate' is usable:

arr3  = np.concatenate((arr1, arr2), axis=0)
Sign up to request clarification or add additional context in comments.

2 Comments

np.append takes 2 arguments, tweaks them a bit, and then calls concatenate((arg1, arg2), axis=axis). It's ok when used once, but too many users try to use it in a loop. It's better to collect a list of arrays (list append is more efficient) and do one concatenate at the end. Plus defining that initial "empty" array is tricky for most beginners.
About the storing data in a list and then make array from that I do agree that it is much faster.

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.