How does a lambda function work in Pandas
Suppose we wish to perform any operation on row or column of dataset. Now we can do it through a loop or set up a lambda function for the same.
So this recipe is a short example on How does a lambda function work in Pandas. Let's get started.
import pandas as pd import seaborn as sb
Let's pause and look at these imports. Pandas is generally used for performing mathematical operation and preferably over arrays. Seaborn will help us in importing dataset.
df = sb.load_dataset('tips') print(df.head())
Here we have imported datset from seaborn library.
Now, our dataset is ready.
df = df.assign(Percentage = lambda x: (x['tip'] /x['total_bill'] * 100)) print(df.head())
Now we are creating a newcolumn of percentage as tip vs total bill.
Once we run the above code snippet, we will see:
Scroll down the ipython file to visualize the final output.
We can see a new column of Percentage being created with the formula as mentioned above.