Lambda with if statement - python

Let say I have a list called "y_pred", I want to write a lambda function to change the value to 0 if the value is less than 0.
Before: y_pred=[1,2,3,-1]
After: y_pred=[1,2,3,0]
I wrote something like this, and return an error message
y_pred=list(lambda x: 0 if y_pred[x]<0 else y_pred[x])
TypeError: 'function' object is not iterable

You want an expression (a if cond else b) mapped over your list:
y_pred_before = [1, 2, 3, -1]
y_pred_after = list(map(lambda x: 0 if x < 0 else x, y_pred_before))
# => [1, 2, 3, 0]
A shorter form of the same thing is a list comprehension ([expr for item in iterable]):
y_pred_after = [0 if x < 0 else x for x in y_pred_before]
Your error "TypeError: 'function' object is not iterable" comes from the fact that list() tries to iterate over its argument. You've given it a lambda, i.e. a function. And functions are not iterable.
You meant to iterate over the results of the function. That's what map() does.

You can use numpy (assuming that using lambda is not a requirement):
import numpy as np
y_pred = np.array(y_pred)
y_pred[y_pred < 0] = 0
y_pred
Output:
array([1, 2, 3, 0])

An easy way to do this with list comprehension:
y_pred=[x if x>0 else 0 for x in y_pred_before]

Related

Change instance of y to z in x(where x is a list)

I wrote a function that changes all instances of y to z in x (where x is a list) but somehow my code is not working. The outcome should have been [1, 'zzz', 3, 1, 'zzz', 3]. I attached my code below any help is appreciated. Thanks in advance.
x = [1, 2, 3, 1, 2, 3]
def changeThem(x,y,z):
replace = {y : z}
for key, value in replace.items():
x = x.replace(key, value)
print(x)
changeThem(x,2,'zzz')
A list does not have .replace() method. How about the following?
x = [1, 2, 3, 1, 2, 3]
def changeThem(x,y,z):
return [z if i == y else i for i in x]
print(changeThem(x, 2, 'zz'))
The function consists of just one line so defining this function might not be even necessary. But I am leaving it in case you would like to call it multiple times.
Your code yields an AttributeError. This is because list does not have a replace method. str has a replace method, so this might be where you're getting confused.
You could accomplish this with a very simple list comprehension:
x = [z if e == y else e for e in x]
Essentially, the above list comprehension states:
For every value e in the list x, replace it with z if the element is equal to y. Otherwise, just keep the element there.
It is also equivalent to the following:
result = []
for e in x:
if e == y:
result.append(z)
else:
result.append(x)

How can I remove a certain element from an array?

I have a Python array.
arr = [1, 2, 3, 4, 5]
I want to remove N with a certain condition from the arr and store it again in the arr.
The condition: the remainder divided by 2 is 0 (it can be any other condition depending on the context)
For example, when removing N the remainder divided by 2 is 0, the result should be [1, 3, 5]. I want to use lambda for this but I don't know how.
Using JavaScript I can do this like this.
How can I achieve this?
If you lop through the array and remove any values with remainders you will get the desired affect:
This is how:
arr = [1,2,3,4,5]
#Loops through the array and removes values with a remaider
arr = [N for N in arr if N%2 != 0]
print(arr)
Output:
[1 , 3 ,5]
As you want a generic solution where you can change the formula, the normal Pythonic approach to this would be use a conditional logic in a list comprehension, for example:
arr = [1, 2, 3, 4, 5]
arr = [x for x in arr if x%2 != 0]
This recreates the list only with elements that match your criterion (so, as you want to remove elements where x%2 == 0, this flips in the list comprehension to only add items to the list where x%2 != 0.
As you did ask for a method that uses a lambda function, so you could (if you really wanted to, I can't say I recommend it) use:
func = lambda x : [x for x in arr if x%2 != 0]
arr = func(arr)
or
func2 = lambda x : x%2 != 0
arr = [x for x in arr if func2(x)]

relu activation function using lambda

Hi I want to implement a lambda function in python which gives me back x if x> 1 and 0 otherhwise (relu):
so I have smth. like:
p = [-1,0,2,4,-3,1]
relu_vals = lambda x: x if x>0 else 0
print(relu_vals(p))
It is important to note that I want to pass the value of lambda to a function
but it fails....
You want to use map to apply this function on every element of the list
list(map(relu_vals, p))
gives you
[0, 0, 2, 4, 0, 1]
Also it's better to define the lambda function within map if you are not planning to use it again
print(list(map(lambda x: x if x > 0 else 0, p)))
You program is right, but need some modification.
Try this,
>>> p = [-1,0,2,4,-3,1]
>>> relu_vals = lambda x: x if x>0 else 0
>>> [relu_vals(i) for i in p]
[0, 0, 2, 4, 0, 1]

Execute a code block in a map in Python

I want to replicate the following JavaScript code in Python:
let a = [0, 4, 5]
b = a.map(x => {
if(x < 3) return 0
else return 1
})
Any idea how I can do this?
I'm not sure how execute a code block in a map function.
You can either make a function, or use a lambda function like this:
>>> a = [0, 4, 5]
>>> b = map(lambda x: 0 if x < 3 else 1, a)
>>> b
[0, 1, 1]
The only kind of anonymous functions in Python are lambdas, and they're limited to being only an expression, if you want a proper function you have to give it a name:
def map_f(x):
if x < 3:
return 0
else:
return 1
b = map(map_f, a)
Personally, I prefer list comprehension to the map function.
>>> a = [0, 4, 5]
>>> [int(x >= 3) for x in a]
[0, 1, 1]
They allow you to use whatever expression you want without having to create a function.

python map function (+ lambda) involving conditionals (if)

I'm curious if it's possible to do something with the map()function that I can do via list comprehension.
For ex, take this list comp:
example_list = [x*2 for x in range(5) if x*2/6. != 1]
obviously, this gives me [0, 2, 4, 8].
How do I make the equivalent using the map() function? Doing this gives me a syntax error.
example_map = map(lambda x:x*2 if x*2/6. != 1, range(5))
Just trying to get a better understanding of how to use this function.
You'll have to wrap the map around a filter around the list:
example_map = map(lambda x: x*2, filter(lambda x: x*2/6. != 1, range(5)))
Alternatively, you could filter your map rather than maping your filter.
example_map = filter(lambda x: x/6. != 1, map(lambda x: x*2, range(5)))
Just remember that you're now filtering the RESULT rather than the original (i.e. lambda x: x/6. != 1 instead of lambda x: x*2/6. != 1 since x is already doubled from the map)
Heck if you really want, you could kind of throw it all together with a conditional expression
example_map = map(lambda x: x*2 if x*2/6. != 1 else None, range(5))
But it'll leave you with [0, 2, 4, None, 8]. filter(None, example_map) will drop the Nones and leave you [0, 2, 4, 8] as expected.
Along side the other answers that suggests some solutions the reason of your Syntax Error is that map function :
Apply function to every item of iterable and return a list of the results.
So the result is in a same length as your iterable.and if you use if statement you need to specify an else too.
>>> map(lambda x:x*2 if x*2/6. != 1 else None, range(5))
[0, 2, 4, None, 8]
And as an alternative way you can use itertools.ifilter to filter your iterable :
>>> from itertools import ifilter
>>> map(lambda x:x*2,ifilter(lambda x: x*2/6. != 1,range(5)))
[0, 2, 4, 8]
Note that as you don't need the result of filtered list and you just want to pass it to map it's more efficient that use ifilter because it returns a generator and you can save much memory for long lists ;) (its all in python 2 and in python 3 filter returns generator)
you can do it at two stages, first stage by applying filter on the list and the second stage by applying mapping function on the output list
list(map(lambda x:x*2, filter(lambda x: x*2/6 != 1 , [x for x in range(5)])))
[0, 2, 4, 8]

Categories

Resources