[英]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.]
我的问题更多是关于如何将子数组传递给numpy.vectorize-d函数,而不是专门针对此示例。
I can't figure out how to use numpy.vectorize or numpy.frompyfunc to vectorize commands that takes an array as an argument. 我不知道如何使用numpy.vectorize或numpy.frompyfunc来矢量化将数组作为参数的命令。
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): 让我们考虑一个简单的示例(我理解这是一个非常基本的示例,而我根本不必使用numpy.vectorize。我只是想举一个示例):
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. 我想向量化一个将aa和bb的每个子数组的第二个元素相加的函数。 In this example I want to return an array of [202 203 206 210]
在此示例中,我想返回一个数组[202203206210]
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. 与numpy.frompyfunc类似的事情没有运气。
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? 我的问题是,如何将子数组列表放到numpy.vectorize-d函数中,并让每个子数组作为该函数的参数?
One of your problems is that aa and bb are lists, not numpy.array()
. 您的问题之一是aa和bb是列表,而不是
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]
. 我注意到的第二件事是,要获取每个子数组的第二个元素,您需要
aa[:,1]
,而不是aa[2]
。
Third, your vec2
function should return
something, not just print
. 第三,您的
vec2
函数应该return
某些内容,而不仅仅是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. 最后一个问题是,您的
vec2
函数应该对整数而不是数组进行运算,并且应该将切片传递给函数,而不是完整的数组。 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. 注意OP帖子上的EDIT,这使答案似乎有些奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.