0
df['expens'] = df.apply(lambda z : z['total_bill'] * 2  if z['total_bill'] < 10 ,axis = 1)

I want to apply the lambda expression using the if condition and create new column variable df['expens'] under the condition if df['total_bill] is < 10

I tried the above the python syntax but is throws an error "invalid syntax"

ljmc
  • 4,830
  • 2
  • 7
  • 26
  • 1
    What do you expect the function to do if `z['total_bill']` is *not* less than 10? – chepner Jan 09 '23 at 20:12
  • 1
    `df.loc[df['total_bill'] < 10, 'expens'] = df['total_bill'] * 2` – mozway Jan 09 '23 at 20:13
  • 1
    A conditional expression *must* include values for when the condition is both true and false. If you only want to apply the function to a subset of the column, you need to filter the column first, then apply an unconditional function to the result. – chepner Jan 09 '23 at 20:13
  • Welcome back to Stack Overflow! Please read [ask], which has tips like how to write a good title. – wjandrea Jan 09 '23 at 20:14
  • My point is that how to use lambda function to get the above . I am aware of the .loc function. – BennoDominic Jan 10 '23 at 07:55

1 Answers1

3

Apply the condition during indexing, not in the lambda if you only want to apply the function to those rows for which the condition is true. Also no need for a lambda if just multiplying in pandas.

df.loc[df["total_bill"]<10, "expens"] = df["total_bill"] * 2

NB. it is possible to have a condition in a lambda with the ternary operator lambda x: x * 2 if x < 10 else x but not useful in this case.

ljmc
  • 4,830
  • 2
  • 7
  • 26
  • def yelp(price): if price < 10: return '$' elif price >= 10 and price < 30: return '$$' else: return '$$$' df['Expensive'] = df['total_bill'].apply(yelp) ,how to use lambda to obtain yelp function – BennoDominic Jan 10 '23 at 09:51