group by tx rx and max msg

import pandas
import random
df = pandas.DataFrame(columns=['tx','rx','part','max','msg'])
newdata=pandas.Series({'tx':random.randint(0,100),'rx':random.randint(0,100),'part':random.randint(1,3),'max':random.randint(1,3),'msg':'hi tim'})
df=df.append(newdata,ignore_index=True)
df
import pandas
import pprint
df = pandas.DataFrame(columns=['tx','rx','part','max','msg'],index=['tx','rx','part','max'])
fake=[[1,2,1,3,'T Part 1 of 3'],
      [1,2,2,3,'T Part 2 of 3'],
      [1,2,3,3,'T Part 3 of 3'],
      [3,4,1,1,'J Part 1 of 1'],
      [4,5,1,1,'B Part 1 of 1'],
      [1,2,1,1,'T Part 1 of 1'],
      [8,9,1,2,'Bob Part 1 of 1'],
      [8,9,1,2,'Bob Part 2 of 2'],

     ]


df = pandas.DataFrame(columns=['tx','rx','part','max','msg'])
for i in range(0,len(fake)):
    pprint.pprint(fake[i])
    df.loc[i]=fake[i]
df
[1, 2, 1, 3, 'T Part 1 of 3']
[1, 2, 2, 3, 'T Part 2 of 3']
[1, 2, 3, 3, 'T Part 3 of 3']
[3, 4, 1, 1, 'J Part 1 of 1']
[4, 5, 1, 1, 'B Part 1 of 1']
[1, 2, 1, 1, 'T Part 1 of 1']
[8, 9, 1, 2, 'Bob Part 1 of 1']
[8, 9, 1, 2, 'Bob Part 2 of 2']
tx rx part max msg
0 1 2 1 3 T Part 1 of 3
1 1 2 2 3 T Part 2 of 3
2 1 2 3 3 T Part 3 of 3
3 3 4 1 1 J Part 1 of 1
4 4 5 1 1 B Part 1 of 1
5 1 2 1 1 T Part 1 of 1
6 8 9 1 2 Bob Part 1 of 1
7 8 9 1 2 Bob Part 2 of 2
#Group by tx rx and max_msg 
df.groupby(['tx','rx','max']).groups.keys()
dict_keys([(8.0, 9.0, 2.0), (4.0, 5.0, 1.0), (3.0, 4.0, 1.0), (1.0, 2.0, 1.0), (1.0, 2.0, 3.0)])
#Try and group the next together
df.groupby(['tx','rx','max']).apply(lambda x: x.sum())
tx rx part max msg
tx rx max
1 2 1 1 2 1 1 T Part 1 of 1
3 3 6 6 9 T Part 1 of 3T Part 2 of 3T Part 3 of 3
3 4 1 3 4 1 1 J Part 1 of 1
4 5 1 4 5 1 1 B Part 1 of 1
8 9 2 16 18 2 4 Bob Part 1 of 1Bob Part 2 of 2
#Sort
df.sort_values(by=['tx','rx','part','max'], ascending=False )
tx rx part max msg
6 8 9 1 2 Bob Part 1 of 1
7 8 9 1 2 Bob Part 2 of 2
4 4 5 1 1 B Part 1 of 1
3 3 4 1 1 J Part 1 of 1
2 1 2 3 3 T Part 3 of 3
1 1 2 2 3 T Part 2 of 3
0 1 2 1 3 T Part 1 of 3
5 1 2 1 1 T Part 1 of 1
#Ok Now sort and Group by
#Limit the columns to 3
d_new=df.sort_values(by=['tx','rx','part','max'], ascending=True ).groupby(['tx','rx','max']).apply(lambda x: x.sum())
d_new.reset_index(drop=True)
tx rx part max msg
0 1 2 1 1 T Part 1 of 1
1 3 6 6 9 T Part 1 of 3T Part 2 of 3T Part 3 of 3
2 3 4 1 1 J Part 1 of 1
3 4 5 1 1 B Part 1 of 1
4 16 18 2 4 Bob Part 1 of 1Bob Part 2 of 2
aggregations = {

    'max':  lambda x: max(x),
    'msg': lambda x: x.sum(),
    'part': ["count"]
    }
df.sort_values(by=['tx','rx','part','max'], ascending=True ).groupby(['tx','rx','max']).agg(aggregations)
max part msg
<lambda> count <lambda>
tx rx max
1 2 1 1 1 T Part 1 of 1
3 3 3 T Part 1 of 3T Part 2 of 3T Part 3 of 3
3 4 1 1 1 J Part 1 of 1
4 5 1 1 1 B Part 1 of 1
8 9 2 2 2 Bob Part 1 of 1Bob Part 2 of 2