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.
Related
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'])
I would like to use a lambda function to return values. This could be handled in a function, however would prefer the use of lambda for this exercise. In general, I want to have the lambda return either a date or 0 by passing a second parameter.
import datetime
none_func=lambda x: 0 if x is None else x
print(none_func(None))
print(none_func(7))
print(none_func(datetime.datetime(2020,1,1)))
### Here, update the lambda function to take an additional parameters, like returns a date if None as well
none_func=lambda x: datetime.datetime(1900,1,1) if x is None else x
print(none_func(None))
print(none_func(7))
Updated for clarification:
I would like to convert the coalesce function to a lambda.
def coalesce(x,return_schema='int'):
if x is None and return_schema=='int': return 0
elif x is None and return_schema=='date': return datetime.datetime(1900,1,1)
else: return x
print(coalesce(7))
print(coalesce(None))
print(coalesce(None,return_schema='date'))
print(coalesce(datetime.datetime.today(),return_schema='date'))
Use the function would be a better option, but if you want to convert it to lambda you can try something like this:
import datetime
f = lambda x,return_schema="int": 0 if x is None and return_schema=='int' else ( datetime.datetime(1900,1,1) if x is None and return_schema=='date' else x)
print(f(7))
print(f(None))
print(f(None, return_schema='date'))
print(f(datetime.datetime.today(), return_schema='date'))
I hope it helps.
Are you looking for something along the lines of:
func = lambda x, y: 'default' if (x is None or y is None) else x
func(1, 2) # returns 1
func(None, 1) # returns 'default'
func(1, None) # returns 'default'
func(None, None) # returns 'default'
Or if you only want to do something based on the second parameter just change the if statement to test the value of that.
So i have a homework question, but I'm not sure why I got it wrong / how it works.
once = lambda f: lambda x: f(x)
twice = lambda f: lambda x: f(f(x))
thrice = lambda f: lambda x: f(f(f(x)))
print(thrice(twice)(once)(lambda x: x + 2)(9))
My ans: 25 -> 8*2 +9
Actual ans: 11 -> 2 + 9
What I was thinking:
thrice -> f(f(f(x))),
let new_x = twice(x)
thrice -> f(f(new_x)),
let new_x2 = twice(new_x)
thrice -> f(new_x2),
let new_thrice = twice(new_x2)
so afterwards I add in the (once) and did
new_thrice(once)(lambda x: x+2)(9)
But answer seems to be that (once) nullifies the earlier thrice(twice) and am lost about. Would be great if someone has an explanation.. Thanks!
I hope this will help you to figure out what is going on!
once = lambda f: lambda x: f(x)
twice = lambda f: lambda x: f(f(x))
thrice = lambda f: lambda x: f(f(f(x)))
# Created this one to help readability.
custom_func = lambda x: x + 2
print("once:", once(custom_func)(9)) # returns value
print("twice:", twice(custom_func)(9)) # returns value
print("thrice:", thrice(custom_func)(9)) # returns value
print("applying all those:", thrice(custom_func)(twice(custom_func)(once(custom_func)(9))))
# This represents the following: (((9 + 2) + 2 + 2) + 2 + 2 + 2)
# each pair of parenthesis mean one function being applied, first once, then twice, then thrice.
# If I've understood correctly you need to achieve 25
# to achieve 25 we need to apply +4 in this result so, which means +2 +2, twice function...
print("Achieving 25:", twice(custom_func)(thrice(custom_func)(twice(custom_func)(once(custom_func)(9)))))
# That is it! Hope it helps.
once(lambda x: x+2) evaluates to a function that applies lambda x: x+2 to its argument. In other words, it's equivalent to lambda x: x+2.
once(once(lambda x: x+2)) evaluates to a function that applies once(lambda x: x+2) to its argument. In other words, it's also equivalent to lambda x: x+2.
once(once(once(lambda x: x+2))) evaluates to a function that applies once(once(lambda x: x+2)) to its argument. In other words, this is also equivalent to lambda x: x+2. This doesn't change no matter how many times you apply once.
thrice(twice)(once) evaluates to a function that applies once to its argument some number of times. (8 times, not that it matters for the analysis.) once doesn't change a function's behavior. No matter how many times you apply once, the final function only applies the underlying function once.
thrice(twice)(once)(lambda x: x + 2) thus evaluates to a function that does the same thing as lambda x: x + 2.
Now, if it had been thrice(twice)(once(lambda x: x + 2)) (note the moved parentheses), then that would have applied thrice(twice) to once(lambda x: x + 2), and the result would be a function that applies lambda x: x + 2 8 times.
I am trying to understand nested lambdas:
f = lambda x, y: y(y(x))
g = lambda x : lambda y: x(y)
print( f(lambda x: x+1, g) (4) )
I was told that this code printed "5". How is this explained, and how should one parse the (4) in the last line?
From my understanding of lambda, if,
h = lambda a, b : a+b
i know that print(h(1,2)) will give 3
as a = 1, b =2, and proceed with a+b = 1+2 =3
f(lambda x: x+1, g) ultimately returns another function. That function is then called with 4 as its argument to produce the final result of 5.
Let h = lambda x: x + 1, because this becomes a mess to trace otherwise.
First, we apply f to h and g.
f(h, g)(4) == (lambda x,y: y(y(x))(h, g)(4)
== g(g(h))(4)
Next, we'll evaluate the inner call to g:
g(g(h))(4) == g((lambda x: lambda y: x(y))(h))(4)
== g(lambda y: h(y))(4)
== g(h)(4)
The last step is an example of eta reduction, to use a term from lambda calculus: a function that applies a second function to an argument is equivalent to the second function itself.
Finally, we evaluate g(h) again the same way, which finally gets us to an expression that doesn't involve passing a function as an argument, and lets us get a final answer.
g(h)(4) == (lambda y: h(y))(4)
== h(4)
== (lambda x: x + 1)(4)
== 4 + 1
== 5
Let's have a go at expanding the logic. First, I'm going to rename some argument names to differentiate your two functions:
f = lambda i, j: j(j(i))
g = lambda x: lambda y: x(y)
Now f(lambda x: x+1, g) is equivalent to:
h = (lambda i, j: j(j(i)))(lambda x: x+1, g)
Here, a function being used as an argument. This is fine, as functions are first-class objects in Python and can be passed around in this way. So evaluating this:
h = g(g(lambda x: x+1))
But g is nothing fancy, it simply takes a function and applies it to an argument. It can be considered an "identity" function with a function as an argument. You can get rid of g altogether. So we have:
h = (lambda x: x+1)
In other words, h just adds one to any input.
h = lambda x: x+1 is a function that returns 1 more than the value passed to it. It is equivalent to:
def h(x):
return x+1
f = lambda x, y: y(y(x)) is a function which takes a value and a function as a pair of arguments and evaluates function(function(value)).
It is equivalent to:
def f(x, y):
return y(y(x))
g = lambda x: lambda y: x(y) is a decorator function that returns a new function based on function passed to it.It is equivalent to:
def g(x):
def new_func(y):
return x(y)
return new_func
the given lambda expressions,
f = lambda x, y: y(y(x))
g = lambda x : lambda y: x(y)
expression to evaluate
f(lambda x: x+1, g) (4)
this reduces to
=> g(g(lambda x: x+1)) (4)
now note that g(g(lambda x: x+1)) returns a function g(lambda x: x+1)
=> g(lambda x: x+1) (4)
now here g(lambda x: x+1) again returns a function (x+1)
=> (x+1) (4)
this evaluates to 4+1 i.e 5
=> 5
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.