0

This code..

array = np.array([[1, 2, 3], [3, 4, 5]])
for k in range(0, len(array)):
    final_array = np.hstack(array[k, :])
print(final_array)

Will only print the last [3,4,5] not the entire array in an hstack.

I tried doing final_array += np.hstack(array[k, :]), but Python gives me an error. Also tried to reshape the array before concatenation.

My goal is to add the array items to the hstack in reverse order so I think I need to use a loop -- and not just insert the entire array into an hstack call.

All the examples I've found online are simple where you have two arrays and you call hstack. But, I haven't found any that combine successive arrays in a loop.

I'm assuming this is simple, but the solution escapes me.

Thanks in advance for suggestions.

0

1 Answer 1

3

Your loop keeps overwriting final_array with a new value, so at the end you're left with just that from the last loop iteration.

Building arrays using loops like this is losing game, it is very slow. Instead, just say np.hstack(array) and get it all done in one go. This will be 10-100x faster.

Sign up to request clarification or add additional context in comments.

3 Comments

Brilliant. I missed that simple solution! Thank you. It works great.
One question though ... what if I need to reverse the order of the array items in the final hstack? That's why I was using a loop. Can't figure out how to do that.
@Morkus: You mean you want [3, 4, 5, 1, 2, 3] ? Then just do np.hstack(array[::-1]) to reverse the input before stacking.

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.