开发者

how to use numpy.vectorize or numpy.frompyfunc

[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 ou开发者_JS百科t 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:

aa = np.array([[1,2,3,4], [2,3,4,5], [5,6,7,8], [9,10,11,12]])
bb = np.array([[100,200,300,400], [100,200,300,400], [100,200,300,400], [100,200,300,400]])

The second thing I notice is that to get the second element of each subarray, you need aa[:,1], not aa[2].

Third, your vec2 function should return something, not just print.

The final issue is that your vec2 function 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:

import numpy as np
aa = np.array([[1,2,3,4], [2,3,4,5], [5,6,7,8], [9,10,11,12]])
bb = np.array([[100,200,300,400], [100,200,300,400], [100,200,300,400], [100,200,300,400]])

def vec2(a, b):
    return a + b

func2 = np.vectorize(vec2)
print func2(bb[:,1], aa[:,1])

Note EDITS on OP's post which make this answer seem a bit odd.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜