Is there a way to create a lambda equivalent of this function call in Pandas?

28 Views Asked by At

Using this function and call:

  def top(df, n=3, column='tip_pct'):
      return df.sort_values(by=column, ascending=False)[:n]

  tips.groupby('smoker').apply(top)

I was able to obtain this output:

enter image description here

Is there a way to show the same output using a lambda function?

1

There are 1 best solutions below

0
Barmar On

Since the function is a one-liner, you can just copy the return expression into the body of the lambda.

tips.groupby('smoker').apply(lambda df, n=3, column='tip_pct': df.sort_values(by=column, ascending=False)[:n])