Petal Power Inventory Doubt

Hello, I want to know what is the difference between both codes, one is the one I made and the other one is the one shown is the walkthrough video.

inventory[“total_value”] = inventory.price * inventory.quantity

inventory[“total_value”] = inventory.apply(lambda row: row.price * row.quantity, axis=1)

Link to the project: https://www.codecademy.com/paths/finance-python/tracks/introduction-to-pandas-for-finance/modules/introduction-to-pandas-python-finance/projects/pandas-inventory-proj

Hi there.

They both do the same thing.

inventory['total_value'] = inventory.price * inventory.quantity creates a new column, setting each value in the column to the value of inventory.price * inventory.quantity for each row.

inventory['total_value'] = inventory.apply(lambda row: row.price * row.quantity, axis=1) is telling Pandas to create the new column total_value, and then to apply the lambda function along the column. (axis=1 means apply the function to the column, so it calculates price * quantity for each row in the column.)

Not sure if my explanation will help, but essentially they both will have the same result - they’re just different ways of getting there.

1 Like

I had this same question for the inventory[‘in_stock’] column. (I did the same total_value as you, OP, and came here to see if there was a difference in my code.)
Is there a tangible difference, rather than style, between my first code and the instructor’s code? Is lambda more efficient?
My code:
inventory['in_stock'] = inventory.quantity.apply(lambda x: True if x>0 else False)
Video Tutorial Code:
inventory['in_stock'] = inventory.apply(lambda row: True if row.quantity >0 else False, axis = 1)
They yielded the same result.