how to slice and combine specific row values in a Pandas groupby?
<p>Consider the following dataframe</p>

<pre><code>df = pd.DataFrame({'group1' : ['A', 'A', 'A', 'A',
                         'A', 'A', 'A', 'A'],
                   'group2' : ['C', 'C', 'C', 'C',
                         'C', 'E', 'E', 'E'],
                   'time' : [-6,-5,-4,-3,-2,-6,-3,-4] , 
                   'col': [1,2,3,4,5,6,7,8]})

df
Out[36]: 
   col group1 group2  time
0    1      A      C    -6
1    2      A      C    -5
2    3      A      C    -4
3    4      A      C    -3
4    5      A      C    -2
5    6      A      E    -6
6    7      A      E    -3
7    8      A      E    -4
</code></pre>

<p>my objective is to create a column that contains, for each group in <code>['group1','group2']</code> the ratio of <code>col</code> evaluated at <code>time = -6</code> divided by <code>col</code> evaluated at <code>time = -4</code>. </p>

<p>That is, for group <code>['A','C']</code>, I expect this column to be equal to 1/3, for group <code>['A','E']</code> it is 6/8. Both <code>group1</code> and <code>group1</code> take on many different values in the data.</p>

<p>How can I get that in Pandas?</p>

<p>Something like </p>

<pre><code> df.groupby(['group1','group2']).transform(lambda x: x.ix[x['time'] == -6,'col'] / x.ix[x['time'] == -4,'col'])
</code></pre>

<p>does not work..
Any ideas?</p>

<p>Thanks!</p>

<p>You could do it without <code>groupby</code> like this:</p>

<pre><code>dfm = pd.merge(df[df.time == -4],df[df.time == -6],on=["group1","group2"])
dfm['Div'] = dfm.col_y.div(dfm.col_x)
df = pd.merge(df,dfm[['group1','group2','Div']],on=["group1","group2"])
</code></pre>

<p>Output:</p>

<pre><code>   col group1 group2  time       Div
0    1      A      C    -6  0.333333
1    2      A      C    -5  0.333333
2    3      A      C    -4  0.333333
3    4      A      C    -3  0.333333
4    5      A      C    -2  0.333333
5    6      A      E    -6  0.750000
6    7      A      E    -3  0.750000
7    8      A      E    -4  0.750000
</code></pre>

python pandas