Optimisation of the group_by function