Improve groupby and cache functions