Complicated GroupingComplicated Grouping

It is sometimes the case that we aren't satisfied with built-in pandas functions, like .mean() or .min() while grouping.

Look at the column 'Length'; here, we have the flight length in minutes. Imagine we want to calculate the maximum time in hours for items having the same value in the 'Flight' column and then in the 'Airline' one. To do so, we can calculate the maximum value of the column 'Length' for each group key and then divide it by 60. Look at the example and the explanation below.


We made the example from the previous chapters a little bit complicated, so with data grouping, everything is the same; let's turn to the .apply() function.

  • .apply() - it helps apply specific function to the needed columns.
  • in the lambda function, x is the argument and x['Length'].max()/60 is the expression. So, the function finds the maximum value for each group key and divides the aggregated value by 60.


Your task here is to group data by the airport from which the flight started and then by the weekday. Calculate the minimum amount of time of the sum of the groups' columns 'Length' and 'Time' for the groups to figure out how long the flight with delay may take. Follow the algorithm to manage the task:

  1. Group data:
  • Extract the columns 'AirportFrom', 'Airline', 'Time', and 'Length' from data (in this order).
  • The order is crucial within the .groupby() function; put the columns 'AirportFrom' and 'Airline' in this order.
  • Apply the function to the values of the data set having the same group keys.
  • Calculate the sum of two columns: 'Length' and 'Time'. Then find their minimum.

Everything was clear?

Section 4. Chapter 3
toggle bottom row