Home > Software engineering >  Using ternary statement in a lambda function
Using ternary statement in a lambda function

Time:11-12

I've been trying to round a vector of a DataFrame using a lambda function. In my vector I also have string values, so I tried this code:

dff.apply(lambda x: round(x, 2) if (isinstance(x,float)))

But it raises a SyntaxError.

CodePudding user response:

Ternary statement in Python require else after the condition.

dff.apply(lambda x: round(x, 2) if (isinstance(x,float)) else x)

CodePudding user response:

There are two problems here:

  1. tenary if-else missing the else statement. Like answered by user17242583.
  2. dff.apply digest column by column, thus the isinstance(x,float) will not work for rounding. Use the vectorized numpy.round instead.
dff.apply( lambda x: np.round(x,2))
  • Related