I have an array of numbers, and a list of functions.
I want to run every function on every number to get back a matrix.
Is there a way to do it without slow python for looping / mapping?
import numpy
arr = numpy.array([1,2,3,4,5])
fns = [numpy.sin, numpy.cos, numpy.exp]
results = numpy.zeros(shape=( len(fns), len(arr) ))
for i, fn in enumerate(fns):
for j, val in enumerate(arr):
results[i][j] = fn(val)
print ('results', results)
I can get rid of one loop with function broadcasting:
results2 = numpy.zeros(shape=( len(fns), len(arr) ))
for i, fn in enumerate(fns):
results2[i] = fn(arr)
print ('results2', results2)
Is there some clever pythonic numpy-ish way to get rid of my second loop?
Perhaps some built in outer-product-ish interaction which is difficult to google?
results3 = numpy.function_outer( fns, arr)
fns. You could create a lambda function and use numpy'sfrompyfuncorapply_along_axis, but this will just marginally slow things down.