1

I have 5 numpy arrays with shape (5,5). What I want to achieve is to combine these 5 numpy arrays to one array of shape (5,5,5). My code looks like the following but does not work:

combined = np.empty((0, 5, 5), dtype=np.uint8)

for idx in range(0, 5):
    array = getarray(idx) # returns an array of shape (5,5)
    np.append(combined, img, axis=0)

I thought if I set the first axis to 0 it will append on this axis so that in the end the shape will be (5,5,5). What is wrong here?

2 Answers 2

1

I have figured it out by myself:

combined = np.empty((0, 5, 5), dtype=np.uint8)

for idx in range(0, 5):
    array = getarray(idx) # returns an array of shape (5,5)
    array array[np.newaxis, :, :]
    combined = np.append(combined, img, axis=0)
print combined.shape + returns (5,5,5)
Sign up to request clarification or add additional context in comments.

Comments

0

I'd try:

A = np.array([getarray(idx) for idx in range(5)])

Or

alist = []
for idx in range(5):
   alist.append(getarray(idx))
A = np.array(alist)

Appending to a list is faster than appending to an array. The latter makes a totally new array - as you discovered.

dynamically append N-dimensional array - same issue, starting with different dimensions.

4 Comments

I have already answered my question. But thank you. Why did you bring up another answer? Do you think it is better?
Yes, I think it is faster. You can stick with your np.append, but look at its code so you understand what it is doing. And try some simple time tests. Building arrays incrementally is a frequent SO question.
Yeah I do not need speed. I just need to get it done. But thanks anyway!
Do you mind editing my answer and add your code to it? Then I will accept it. Because both of them are correct I think.

Your Answer

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