2

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
RavinderSingh13
135k14 gold badges61 silver badges100 bronze badges
asked Apr 28, 2022 at 6:53
1
  • 3
    You can use list comprehension for this y_pred=[i if i >= 0 else 0 for i in y_pred] Commented Apr 28, 2022 at 6:56

3 Answers 3

7

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.

answered Apr 28, 2022 at 6:57
Sign up to request clarification or add additional context in comments.

3 Comments

Even simpler: [max(0, y) for y in y_pred]
@flakes True, but this was not meant to be code golf. :) I wanted to keep the OP's ternary.
Just pointing it out! I did +1 the answer!
0

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])
answered Apr 28, 2022 at 7:00

Comments

0

An easy way to do this with list comprehension:

y_pred=[x if x>0 else 0 for x in y_pred_before] 
answered Apr 28, 2022 at 7:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.