sped up code 10x using pandas sums, multi-indexing and groupby