Since version, 0.16.0, pandas has offered the assign()
method. I'm not sure exactly how it compares to pandas-ply as mentioned by @akrun, but it is part of pandas proper. I think that would handle all of your needs except maybe the groupby part (or possibly I just don't know how to combine with groupby).
Documentation for pandas assign
Inspired by dplyr’s mutate verb, DataFrame has a new assign() method. The function signature for assign is simply **kwargs. The keys are the column names for the new fields, and the values are either a value to be inserted (for example, a Series or NumPy array), or a function of one argument to be called on the DataFrame. The new values are inserted, and the entire DataFrame (with all original and new columns) is returned.
Looking at your example code, I'm not sure how to do the groupby, but you certainly can do this sort of thing. (Actually, I may post a followup SO question if I can't figure it out.)
df.assign( mean_weight = lambda x: x['weight'].mean(),
var_time = lambda x: x['time'].var(),
covar = lambda x: np.cov(x.t1,x.t2)[0,0] )
Or, can do it like this:
df.assign( mean_weight = df['weight'].mean(),
var_time = df['time'].var(),
covar = np.cov(df['t1'],df['t2'])[0,0] )
Alternatively, you could include the groupby like this (mixing the alternate ways below):
df.assign( mean_weight = df['weight'].groupby(df.diet).transform('mean'),
var_time = lambda x: x['time'].groupby(x['diet']).transform('mean') )
But you have to do a groupby 4x, not 1x, so that's not real satisfying as a solution...
I'll play around with that syntax a little more and see if I can get it closer to your example (you may want to provide sample data for a better answer).
Alternatively you can do standard groupby techniques to get your answer, but I think it takes multiple statements (can't just do one long chained line) because of the complexity -- some of your assignments can be combined with groupby's agg
but I don't think the user function can.