I have created a pandas dataframe mn using following input:
keyA state n1 n2 d1 d2
key1 CA 100 1000 1 2
key2 FL 200 2000
Pretty much just write it like your pseudocode.
In [14]: s = mn.groupby(['keyA','state'], as_index=False).sum()
In [15]: s['v1'] = s['n1'] / s['d1']
In [16]: s['v2'] = s['n2'] / s['d2']
In [17]: s[['keyA', 'state', 'v1', 'v2']]
Out[17]:
keyA state v1 v2
0 key1 AL 100 500.000000
1 key1 CA 100 500.000000
2 key1 NY 100 1500.000000
3 key2 CA 100 1166.666667
4 key2 FL 100 1166.666667
[5 rows x 4 columns]
I think you have a typo in your example data by the way. The second n1
header should be n2
.