Putting this at the top should eliminate duplicating most of the code for groupby scenario
if groupby:
  column = groupby + '.' + column