Q#40: Calorically dense foods

Suppose you are given the following dataframe containing food, weight, and calories. You’ll notice the foods have varying weights associated with them:

Using Python (Pandas), can you sort the dataframe in descending order with the most calorically dense food (normalized for weight) at the top?

TRY IT YOURSELF

https://colab.research.google.com/drive/12eZ2JRfmHUZuISKt75MMTslPmnw5TxLc?usp=sharing

ANSWER

This question tests your understanding of the Pandas library in Python. The task is to create a new column in the Pandas dataframe object and then sort by that new column.

The first step is to create the column, which in Pandas can be done simply by calling a mathmatical operation on the existing columns in the dataframe. In this case dividing the calories by the grams.

df['caloric_density'] = df['calories']/df['grams']

Finally, all we have to do is sort by this column in descending fashion. To do this we take advantage of the pandas dataframe .sort_values() which sorts by a column we specify. Additionally, to make it a descending sort, we can add the keyword argument ascending = False.

df = df.sort_values(by = 'caloric_density', ascending = False)

And we are done!

--

--