pydata/pandas — pull request #3242 by y-p (2013-04-02 17:42:34+00:00)
Title: ENH: groupby().apply(f) accepts raw arg, to return results unmolested #3241

#3241
Right now:
```python

In [16]: df=mkdf(10,2,data_gen_f=lambda x,y: randint(1,10))
...: df
...:
...:
...:
Out[16]:
C0 C_l0_g0 C_l0_g1
R0
R_l0_g0 9 1
R_l0_g1 3 7
R_l0_g2 8 1
R_l0_g3 4 3
R_l0_g4 5 3
R_l0_g5 7 2
R_l0_g6 4 1
R_l0_g7 5 4
R_l0_g8 9 7
R_l0_g9 4 8

In [17]: def f1(g):
...: return g.sort('C_l0_g0')
...: # group on the suffix of the running index
...: g=df.groupby(lambda key: int(key.split("g")[-1]) >= 5)
...: r=g.apply(f1)
...:

# we want to return each group dataframe sorted, but we get concatted against our will
In [18]: r
Out[18]:
C0 C_l0_g0 C_l0_g1
R0
False R_l0_g1 3 7
R_l0_g3 4 3
R_l0_g4 5 3
R_l0_g2 8 1
R_l0_g0 9 1
True R_l0_g6 4 1
R_l0_g9 4 8
R_l0_g7 5 4
R_l0_g5 7 2
R_l0_g8 9 7

# what we want really, is a couple of sorted dataframes:

In [20]: map(lambda r: r[1].sort('C_l0_g0'),g)
Out[20]:
[C0 C_l0_g0 C_l0_g1
R0
R_l0_g1 3 7
R_l0_g3 4 3
R_l0_g4 5 3
R_l0_g2 8 1
R_l0_g0 9 1,
C0 C_l0_g0 C_l0_g1
R0
R_l0_g6 4 1
R_l0_g9 4 8
R_l0_g7 5 4
R_l0_g5 7 2
R_l0_g8 9 7]
```

#### With this PR:

```python
In [21]: def f1(g): # same f1 as above
...: return g.sort('C_l0_g0')
...: def f2(g,raw=None):
...: return g.sort('C_l0_g0')
...: def f3(g,**kwds):
...: return g.sort('C_l0_g0')
...: # the `raw` keyword is the new bit
...: r1=g.apply(f1,raw=True)
...: r2=g.apply(f2,raw=True)
...: r3=g.apply(f2,raw=True)
...:
# a bunch of sorted frames
In [22]: print r1
[(False, C0 C_l0_g0 C_l0_g1
R0
R_l0_g1 3 7
R_l0_g3 4 3
R_l0_g4 5 3
R_l0_g2 8 1
R_l0_g0 9 1), (True, C0 C_l0_g0 C_l0_g1
R0
R_l0_g6 4 1
R_l0_g9 4 8
R_l0_g7 5 4
R_l0_g5 7 2
R_l0_g8 9 7)]

# but not if the transformer function signature uses **kwds, or 'raw' already
In [23]: print r2
C0 C_l0_g0 C_l0_g1
R0
False R_l0_g1 3 7
R_l0_g3 4 3
R_l0_g4 5 3
R_l0_g2 8 1
R_l0_g0 9 1
True R_l0_g6 4 1
R_l0_g9 4 8
R_l0_g7 5 4
R_l0_g5 7 2
R_l0_g8 9 7

In [24]: print r3
C0 C_l0_g0 C_l0_g1
R0
False R_l0_g1 3 7
R_l0_g3 4 3
R_l0_g4 5 3
R_l0_g2 8 1
R_l0_g0 9 1
True R_l0_g6 4 1
R_l0_g9 4 8
R_l0_g7 5 4
R_l0_g5 7 2
R_l0_g8 9 7
```
```