Constant Lambda Expressions, Shape Of Return Data
A list of lambda expressions given to me (by Sympy's lambdify), some explicitly depending on a variable x, some constant. I would like to evaluate those consistently with Numpy arr
Solution 1:
You could use ones_like
:
>>>X = numpy.array([1, 2, 3])>>>defg(x): return numpy.ones_like(x)>>>g(X)
array([1, 1, 1])
Note that this returns integers, not floats, because that was the input dtype
; you could specify dtype=float
or multiply by 1.0
if you prefer to always get floats out.
PS: It's a little odd to use a lambda
and then immediately give it a name. It's like wearing a mask but handing out business cards.
PPS: back before ones_like
I tended to use x*0+1
when I wanted something appropriately shaped.
Solution 2:
I don't see the problem, just do:
import numpy as np
X = np.array([1, 2, 3])
f = lambda x: 1.0 + x**2print(f(X))
g = lambda x: np.ones(shape=(len(X),))
print(g(X))
Which prints:
[ 2. 5. 10.][ 1. 1. 1.]
Notice that using np.ones(shape=(len(X),))
is the same that using np.ones_like(X)
Solution 3:
Use ones_like
:
g = lambda x: np.ones_like(x) * 1.0
There's also this slightly hackier solution:
g = lambda x: 1.0 + (x*0)
Solution 4:
You seem to want an array of ones:
>>>import numpy>>>numpy.ones(3)
array([ 1., 1., 1.])
If you want to set scalars, it's easy to do so
g = lambda x: numpy.ones(shape=x.shape) * 2
g(X)
returns
array([ 2., 2., 2.])
So for an arbitrary array:
g = lambda x: numpy.ones(shape=x.shape) * 1n = numpy.array([1,2,3,4,5])
g(n) is
array([ 1., 1., 1., 1., 1.])
Post a Comment for "Constant Lambda Expressions, Shape Of Return Data"