The code in the explantion doesn't produce the desired result

I first tried to rewrite the code in the example to help to learn it, and when that didn’t work I copied and pasted from the left pane into the script.py pane. The result should be the array shown of columns 5:9 of rides over 20kmph, but instead I get an array of shape 0, 4.

Screen Link:

My Code:

#calculate the average speed
trip_mph = taxi[:,7] / taxi[:, 8] / 3600
#create a boolean array for trips with average speed > 20Kmph
# use the boolean array to select the rows for
# those trips, and the pickup_location_code,
# dropoff_location_code, trip_distance, and
# trip_length columns
trip_mph_bool = trip_mph > 20000
trip_bool = trips_over_20000_mph = taxi[trip_mph_bool,5:9]

print(trips_over_20000_mph)

What I expected to happen:

What actually happened:

Output
[]

This is your code -

This is the code in the content -

trip_mph = taxi[:,7] / (taxi[:,8] / 3600)

There is a reason that the code in the content has the parentheses.

Not having the parentheses results in a different order of operations because of which you get a different output.

Your code is essentially doing this - (taxi[:,7]/ (taxi[:, 8]) / 3600. . That’s the order of operations in your code (notice the order of the parentheses), which is different from what’s expected.

For a simpler example of the above, print out the following. But before you do that, think about what you expect the result to be -

print(6/2/3, 6/(2/3))

The above should help clear things out.

For future reference, I would also recommend -

  • When facing such differences, make sure to note where the code varies and then work from there to figure out why.
  • When figuring out why, try your best to not make assumptions about how something works.
  • Use print statements and experiment at different stages. For example, in this case it might have helped if you tried both the approaches to calculate trip_mph and also printed out the values. That would have indicated the difference between the two.
1 Like

Thanks, that makes sense.