I'm trying to apply a custom function in pandas similar to the groupby and mutate functionality in dplyr.
What I'm trying to do is say given a pandas dataframe like this:
df = pd.DataFrame({'category1':['a','a','a', 'b', 'b','b'],
'category2':['a', 'b', 'a', 'b', 'a', 'b'],
'var1':np.random.randint(0,100,6),
'var2':np.random.randint(0,100,6)}
)
df
category1 category2 var1 var2
0 a a 23 59
1 a b 54 20
2 a a 48 62
3 b b 45 76
4 b a 60 26
5 b b 13 70
apply some function that returns the same number of elements as the number of elements in the group by:
def myfunc(s):
return [np.mean(s)] * len(s)
to get this result
df
category1 category2 var1 var2 var3
0 a a 23 59 35.5
1 a b 54 20 54
2 a a 48 62 35.5
3 b b 45 76 29
4 b a 60 26 60
5 b b 13 70 29
I was thinking of something along the lines of:
df['var3'] = df.groupby(['category1', 'category2'], group_keys=False).apply(lambda x: myfunc(x.var1))
but haven't been able to get the index to match.
In R with dplyr this would be
df <- df %>%
group_by(category1, category2) %>%
mutate(
var3 = myfunc(var1)
)
So I was able to solve it by using a custom function like:
def myfunc_data(data):
data['var3'] = myfunc(data.var1)
return data
and
df = df.groupby(['category1', 'category2']).apply(myfunc_data)
but I guess I was still wondering if there's a way to do it without defining this custom function.