Fix for non-trivial groupby apply

New unit test also added.