-2

This structure is part of a vastly larger project, but I can't seem to figure out how the lambda portion of this works:

for num in range(1,100):
    dataframe[f'n{num}_bins'] = dataframe[f'n{num}'].apply(
        lambda x: 0 if x < 1
        else 1 if x < 2
        else 2 if x < 3
        else 3 if x < 4
        else 4 if x < 5
        else 5 if x < 6
        else 6

What does lambda check for, exactly?

  • It is used to create in line function. example: ```func = lambda x: print(x)``` is the same as ```def func(x): print(x)``` –  Aug 24 '21 at 13:26

2 Answers2

1

For each row (this is what apply does) in the f'n{num}' column (and for each such column, as per the outer loop):

if the value x at that location is smaller than:

  • 1 -> return 0
  • 2 -> return 1

...

  • 6 -> return 5
  • otherwise (values >=6) -> return 6

Look into Does Python have a ternary conditional operator?

ted
  • 13,596
  • 9
  • 65
  • 107
0

Convert the lambda function to normal function, you will know what's going on:

def func(x):
    if x < 1:
        return 0
    elif x < 2:
        return 1
    elif x < 3:
        return 2
    elif x < 4:
        return 3
    elif x < 5:
        return 4
    elif x < 6:
        return 5
    else:
        return 6

Generally, when you have so many conditions, using lambda is very unpythonic and is not recommended either.

You are confused with above lambda because it appears to be very ambiguous and unreadable.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45