Reputation: 4036
I have a numpy arrary:
import numpy as np
pval=np.array([[0., 0.,0., 0., 0.,0., 0., 0.],
[0., 0., 0., 0., 0.,0., 0., 0.]])
And a vectorized function:
def getnpx(age):
return pval[0]+age
vgetnpx = np.frompyfunc(getnpx, 1, 1)
vgetnpx(1)
The output:
array([1., 1., 1., 1., 1., 1., 1., 1.])
However if I want to set a variable for pval:
def getnpx(mt,age):
return mt[0]+age
vgetnpx = np.frompyfunc(getnpx, 2, 1)
vgetnpx(pval,1)
I received an error:
TypeError: 'float' object is not subscriptable
What is the correct way to set a variable for pval ?Any friend can help?
Upvotes: 0
Views: 349
Reputation: 231738
I don't see why you are trying to use frompyfunc
. That's for passing array arguments to a function that only takes scalar inputs.
In [97]: pval=np.array([[0., 0.,0., 0., 0.,0., 0., 0.],
...: [0., 0., 0., 0., 0.,0., 0., 0.]])
In the first case you use global pval
, and use just 1 age
value. No need to frompyfunc
:
In [98]: pval[0]+1
Out[98]: array([1., 1., 1., 1., 1., 1., 1., 1.])
And if you want to pass pval
as argument, just do:
In [99]: def foo(mt,age):
...: return mt[0]+age
...:
In [100]: foo(pval,1)
Out[100]: array([1., 1., 1., 1., 1., 1., 1., 1.])
You gave a link to an earlier question that I answered. The sticky point in that case was that your function returned an array that could vary in size. I showed how to use it with a list comprehension. I also showed how to tweak vectorize
so it would happy returning an object
dtype result. Alternatively use frompyfunc
to return that object. In all those cases the function argument was a scalar, a single number.
If your goal is to add a different age
to each row of pval
, just do:
In [102]: pval + np.array([[1],[2]])
Out[102]:
array([[1., 1., 1., 1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2., 2., 2., 2.]])
Upvotes: 1