1

With numpy and python3 I have to following problem:

I have a function which returns a 2 dimensional array of integers of fixed size (2x3 in this case). What is the most idiomatic way to run this function n times and stack these together to a 3 dimensional 2x3xn array? What about performance? Something which only does the minimum number of allocations would be nice.

2
  • 2
    For actual performance, it would make sense to know about the implementation of that function itself. It could probably be vectorized with NumPy ufuncs and such. Commented Nov 19, 2015 at 20:00
  • 2
    Something which only does the minimum number of allocations would be nice. - that's C++-style thinking. Allocation isn't what's going to kill your performance in Python. If you try to run this function n times instead of taking advantage of NumPy vectorized operations, interpreter overhead is going to kill your performance. Commented Nov 19, 2015 at 20:25

1 Answer 1

2

You are probably looking for np.dstack:

>>> import numpy as np
>>> arrs = [np.random.rand(2, 3) for x in range(5)]
>>> np.dstack(arrs).shape
(2, 3, 5)

If you know the final shape you can do something like the following:

>>> out = np.empty((2, 3, 5))
>>> out[..., 0] = np.random.rand(2, 3)
Sign up to request clarification or add additional context in comments.

Comments

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.