I have a function:
def function(x):
return x > 0
data['number'] = data['arr_nums'].apply(function)
How do I rewrite this as a lambda function by using pandas? Thanks!
e = lambda a: a>0
print(e(13))e = lambda a: a>0
print(e(13))
you can use like this. If you found it useful, I would appreciate it if you support it :)
Very simple solution:
function = lambda a : a > 0
data['number'] = function(data['arr_nums'])
Related
This works:
C = df_temp['For Team'].map(
lambda x: df_teams.loc[df_teams['CommentName']==x,'TeamColor'].item())
But I would like to add a condition to lambda of x being in another list 'y', like so:
y = ['salah', 'zico', 'pele']
I've tried:
lambda x: df_teams.loc[df_teams['CommentName']==x if x in y,'TeamColor'].item())
But this raises invalid syntax.
How do I do this?
Let us try isin
df_teams.loc[df_teams['CommentName'].isin(y),'TeamColor'].item()
You can always create a named function first and, then, apply that on lambdas.
y = ["salah", "zico", "pele"]
def get_teamcolor(x, y):
if x in y:
return df_teams.loc[df_teams["CommentName"] == x, "TeamColor"].item()
C = df_temp["For Team"].map(lambda x: get_teamcolor(x, y))
This should work:
C = df_temp['For Team'].map(lambda x: df_teams.loc[df_teams['CommentName']==x and x in y,'TeamColor'].item())
You need to join both conditions with an "and" instead of adding an if statement.
I am doing an optimization problem and I'm trying to define a constraint using lambda and def.
Essentially what I want to do is:
lambda x: add_2 if no_added == 2
add_2 is the definition I want to call:
def add_2(x):
lc2 = x[36]-0.02
return lc2
What would be the correct syntax for this?
Just call the funtion and make a default else block:
lambda x: add_2(x) if no_added == 2 else None
Return other value if None do not work for you.
Anyway, you can handle this inside the function:
def add_2(x, no_added):
if no_added == 2:
return x[36]-0.02
return None
I'm still new to python and I was wondering if there was a way to simplify this function into something close to a one-liner:
filters = [lambda x: is_big(x), lambda x: is_wide(x), lambda x: is_gray(x)]
def filter(input):
for func in filters:
if(not func(input)):
return False
else:
continue
return True
Assume the functions in the filters list return booleans. Basically is there any way I can do something like all(apply input to each filter)?
all(func(input) for func in filters)
Yes, you can use all():
result = all(f(input) for f in filters)
Here's a list comprehension to get filtered output from your input:
filtered = [x for x in input if all(f(x) for f in filters)]
You could also use the built in filter:
complete_filter = lambda x: all(f(x) for f in filters)
filtered = filter(complete_filter, input)
On a side note (not sure what others mean by the fact that all doesn't short circuit). See below:
def f():
print "in f"
return True
def g():
print "in g"
return False
def h():
print "in h"
return True
filters = [f, g, h]
print all(fn() for fn in filters)
This prints
in f
in g
False
>>>
Just for curiosity. Discovered Lambdas a few days ago. I was jus wondering if something like that can be done:
(Tried on the interpret but none of my tries seemed to work)
p = lambda x: (lambda x: x%2)/2
There's no explicit purpose. I just did'nt find a satisfactory answer. I may have misunderstood Lambdas.
You can use an inner lambda to return another function, based on the outer parameters:
mul = lambda x: (lambda y: y * x)
times4 = mul(4)
print times4(2)
You aren't actually calling the inner lambda:
p = lambda x: (lambda x: x%2)(x)/2
Note in Python 2 this example will always return 0 since the remainder from dividing by 2 will be either 0 or 1 and integer-dividing that result by 2 will result in a truncated 0.
(lambda x: x%2) is a function, and dividing a function by 2 doesn't make any sense. You probably want to call it and divide what the value it returned.
I'm trying to do the following, which is a representative example of what my final goal will be:
yu = lambda x: 0
for i in range(0,5):
yu = lambda x: i + yu(x)
Unfortunately, it returns:
RuntimeError: maximum recursion depth exceeded
when I do:
print yu(0)
The print statement should return 10.
What's the correct way to do this?
In the end, you have:
yu = lambda x: i + yu(x)
but yu will be looked up at runtime, not when you constructed the lambda. Do this instead:
for i in range(0,5):
yu = lambda x, yu=yu: i + yu(x)
This does not return 10, though. It returns 20 instead:
>>> yu = lambda x: 0
>>> for i in range(0,5):
... yu = lambda x, yu=yu: i + yu(x)
...
>>> yu(0)
20
because now i is still looked up from the context (and by now the loop has finished so it's 4). Solution? Move i to a keyword argument too:
for i in range(0,5):
yu = lambda x, yu=yu, i=i: i + yu(x)
Now this works:
>>> yu = lambda x: 0
>>> for i in range(0,5):
... yu = lambda x, yu=yu, i=i: i + yu(x)
...
>>> yu(0)
10
Moral of the story? Bind your context properly to the scope of the lambda.
yu = lambda x: i + yu(x)
This makes yu into a function that always calls itself, guaranteeing infinite recursion with no base case.
Why? Well, you've built a closure where yu (and i) are the local variables in the function or module that the for loop is part of. That's not what you want; you want to close over the current values of yu and i, not the outer variables.
I'm not sure why you're even using lambda in the first place. If you want to define a function and give it a name, use def.
Here's an easy solution:
def yu(x): return 0
def make_new_yu(yu, i):
def new_yu(x): return i + yu(x)
return new_yu
for i in range(0, 5):
yu = make_new_yu(yu, i)
By making the wrapping explicit, the correct way to do it becomes the most obvious way to do it.
You can, of course, use a lambda inside make_new_yu without making things more confusing:
def make_new_yu(yu, i):
return lambda x: i + yu(x)
And you can even make the initial definition a lambda if you want. But if you insist on not having any def statements, you need to force the right values into the closure in some way, e.g., by using the default-value trick. That's much easier to get wrong—and harder to read once you've done it.
If you want an intuitive understanding of the difference, without learning the details: a function body defines a new scope. So, defining the function (by lambda or def) inside that function means your closure is from that new scope.
I believe I didn't fully understand your question, but could anyone check if this is what he meant?
I assumed you wouldn't need an iterator to generate a list of digits
yu = lambda x: x[0] + yu(x[1:]) if x!=[] else 0
facto = lambda f: f if f == 0 else f + facto(f-1)
print(facto(4))
Considering the answers you try to sum up 0, 1, 2, 3, 4. If that was right you could use the following lambda expression:
yu = lambda x: x + yu(x+1) if x<4 else x
For yu(0) it delivers 10 as a result. The break condition is the value of x which is required to stay smaller than 4 in order to add up.
Assuming that is what you desired to do, you should leave out the loop for a rather concise statement.
This lambda expression differentiates from the others in resulting in different values (other than 10, when not choosing 0 as the parameter x) depending on the given argument.