[EDIT:I sort of brush this example up so I didn’t clean up my code very well. My question is more on, how do I pass a subarray into a numpy.vectorize-d function, not specifically about this example.]
I can’t figure out how to use numpy.vectorize or numpy.frompyfunc to vectorize commands that takes an array as an argument.
Let’s think of this easy example (I understand this is a very basic example and I don’t have to use numpy.vectorize at all. I am just asking for an example):
aa = [[1,2,3,4], [2,3,4,5], [5,6,7,8], [9,10,11,12]]
bb = [[100,200,300,400], [100,200,300,400], [100,200,300,400], [100,200,300,400]]
And I want to vectorize a function that adds up the second element of each subarray of aa and bb. In this example I want to return an array of [202 203 206 210]
But a code like this doesnt work:
def vec2(bsub, asub):
return bsub[1] + asub[1]
func2 = np.vectorize(vec2)
func2( bb, aa )
Similar thing with numpy.frompyfunc has no luck.
My question is, how do I past a list of subarrays into a numpy.vectorize-d function and let each subarray be the argument of the function?
One of your problems is that aa and bb are lists, not
numpy.array(). You should be doing:The second thing I notice is that to get the second element of each subarray, you need
aa[:,1], notaa[2].Third, your
vec2function shouldreturnsomething, not justprint.The final issue is that your
vec2function should operate on integers, not arrays, and you should pass the slices to the function, not the complete arrays. The corrected version (which returns the expected output) is then:Note EDITS on OP’s post which make this answer seem a bit odd.