Python Numpy Outer Product Apply List Of Functions To List Of Arguments Without For Loops

Viewed 128

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)
1 Answers

You can use a list comprehension and transform it back to a numpy array like this:

results3 = numpy.array([ fn(arr) for fn in fns])
Related