Assume I have a function which takes a numpy array of shape (m, k) and I want to apply that function on each element of numpy array of shape (n, m, k).
Naive approach is to iterate through the given numpy array and append the transformed element to an empty numpy array of shape (0, m, k)
result = np.empty(shape=(0, m, k))
for element in elements:
result = np.append(result, [some_operation(element)], axis=0)
What's the efficient way to apply some, let's say, "operation" on numpy array of shape (n, m, k)? I guess there is a more "numpy" approach.
Many thanks.
some_operationis complex it enough the iteration mechanism doesn't matter much; it's callingsome_operationn` times that will take up most time. Butnp.appendis the least efficient; list append is better, or assignment toresult[element, :,:].list(map(f, array))is marginally faster than thelist.appendloop, particularly for very large arrays