Skip to content

Price Gouging Solution


beef_prices.sort_index(inplace=True)
beef_prices_prev = beef_prices.shift(periods=1)
daily_changes = beef_prices - beef_prices_prev
daily_changes.idxmax()
# 9

Explanation

First, use the Series.sort_index() method to sort the Series by its index. Use inplace=True to modify the data in place.

beef_prices.sort_index(inplace=True)

print(beef_prices)
# 0    3.37
# 1    4.64
# 2    3.44
# 3    4.85
# 4    4.36
# 5    3.55
# 6    3.35
# 7    4.78
# 8    3.11
# 9    4.62
# dtype: float64

Now we can interpret the first value of beef_prices as the price of beef on the first day, the second value as the price on the second day, and so on.

Since we want to get the day with the highest increase in price, we need a way to calculate the difference in price from one day to the next. In other words, we need to build a Series where each element represents the change in price from the previous day.

If we had a series to represent the prior day's prices, then we could do beef_prices - prior_day_prices to get the daily price changes. We can accomplish this with the Series.shift() method.

beef_prices_prev = beef_prices.shift(periods=1)

print(beef_prices_prev)
# 0     NaN
# 1    3.37
# 2    4.64
# 3    3.44
# 4    4.85
# 5    4.36
# 6    3.55
# 7    3.35
# 8    4.78
# 9    3.11
# dtype: float64

The shift() method returns the values of a Series offset by some amount.

Using periods=1 means the ith value in the result will return the i-1th value in the original series. In other words, you can imagine the series shifting forward one step, which means we end up with a NaN value at the front of the Series and we discard the value at the back of the Series.

Next, we subtract beef_prices - beef_prices_prev to get the daily price changes.

daily_changes = beef_prices - beef_prices_prev

print(daily_changes)
# 0     NaN
# 1    1.27
# 2   -1.20
# 3    1.41
# 4   -0.49
# 5   -0.81
# 6   -0.20
# 7    1.43
# 8   -1.67
# 9    1.51
# dtype: float64

Lastly, we use the Series.idxmax() method to fetch the index of the largest values in the Series.

daily_changes.idxmax()
# 9

See the problem