1

question: calculate the tip percentage and print Generous if tip >0.25 otherwise print not generous

if i am using lambda function its working fine that why not with a normal function call. i have attached the dataset i'm working with.

enter image description here

dataset

function:

def tip_cal(total_bill, tip):
    if tip/total_bill > 0.25:
        return "Generous"
    else:
        return "fair"

function call:

df[['total_bill', 'tip']].apply(tip_cal(df['total_bill'], df['tip']), axis=1)
ti7
  • 16,375
  • 6
  • 40
  • 68
  • BTW, welcome to Stack Overflow! Check out the [tour], and [How to ask a good question](/help/how-to-ask) for tips. – wjandrea Jul 09 '23 at 17:16
  • I don't think the duplicate fully explains the issue in your case - the problem happens when you try to use `if`, but are passing the _entire column vector_ to `tip_calc` _once_ an then trying to pass that value to `.apply()`, rather than the individual row values - really you want to do one or the other, such as `numpy.where(df['tip'] / df['total_bill'] > 0.25, "Generous", "Fair")` – ti7 Jul 09 '23 at 17:16

1 Answers1

1

The error is happening before the function is even applied. tip_cal(df['total_bill'], df['tip']) calls the function with the whole columns, not the individual values. So you'll need to rework your approach.

I'd use np.where instead of applying a function.

wjandrea
  • 28,235
  • 9
  • 60
  • 81