Home > database >  Lambda with if statement
Lambda with if statement

Time:04-28

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

CodePudding user response:

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.

CodePudding user response:

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])

CodePudding user response:

An easy way to do this with list comprehension:

y_pred=[x if x>0 else 0 for x in y_pred_before] 
  • Related