Help appreciated: Analyze data with python, Introduction to Pandas, Petal Power Inventory Project, Task 6

Hello, could someone please explain to me the difference bewteen these to approaches to Task 6 in the Petal Power Inventory Project in Analze Data with Python Course. The Task is as follows:

Add a column to inventory called in_stock which is True if quantity is greater than 0 and False if quantity equals 0.

Approach 1:

inventory["in_stock"] = inventory.quantity.apply(lambda x: True if x > 0 else False)

Approach 2:

inventory["in_stock"] = inventory.apply(lambda row: True if row.quantity > 0 else False, axis=1)

Thank you for your time.

1 Like


The results are the same, right?

Both functions are using the .apply method to that column, checking each row in that column, “quantity” in the table and applying that logic, “True if x > 0 else False” and then adding the results of the function in that new column, “in_stock”.

The difference, or, my understanding is that with the first lambda function you’re specifying the column in the .apply method, inventory.quantity.apply and the second you’re specifying the column in the logic itself: lambda row: True if row.quantity > 0 else False, axis=1

I’m not sure which one is “better”(cleaner, more efficient?) as I’m not yet advanced enough in my code writing skills. Perhaps someone else can speak to that part.

I’m not sure either. Here is yet another approach to consider that produces the same result:

Approach 3:

inventory['in_stock'] = inventory['quantity'] > 0

Edited on August 30, 2020 to add the following:

The other approaches could be simplified, for example, Approach 2 could be refined to:

inventory["in_stock"] = inventory.apply(lambda row: row.quantity > 0, axis=1)