Q:

how to copy mean values of groupby in all applicable rows in Pandas

I'm following this example and I want to replay using Pandas.  Unfortunately I'm almost immediately stuck: I don't know how to add a column with the mean values per category for all rows. 
My dataframe:
ages = pd. DataFrame(
[[13, 0.0, 1.0, 1.0], 
[14, 0.0, 1.0, 0.0], 
[15, 0.0, 1.0, 0.0], 
[25, 1.0, 1.0, 1.0], 
[35, 0.0, 1.0, 1.0], 
[49, 1.0, 0.0, 0.0], 
[68, 1.0, 1.0, 1.0], 
[71, 1.0, 0.0, 0.0], 
[73, 1.0, 0.0, 1.0]], columns=['age', 'gardening', 'gameing', 'hats'])

I want to add a column with mean age for all persons who (don't) do gardening:
ages['ma'] = ages.groupby('gardening')['age'].mean()

but this gives:
19.5
57.2
6 x NaN

and I want (the first column)
            gardening      age
19.5         0             13
19.5         0             14
19.5         0             15
57.2         1             25
19.5         0             35
57.2         1             49
57.2         1             68
57.2         1             71
57.2         1             73
 ^^

I tried broadcast, transform but this gives not the result I want.  How can I solve this? 

A:

Use groupby with transform:
ages['avg_garden_age'] = ages.groupby('gardening')['age'].transform('mean')
ages

Output:
   age  gardening  gameing  hats  avg_garden_age
0   13        0.0      1.0   1.0           19.25
1   14        0.0      1.0   0.0           19.25
2   15        0.0      1.0   0.0           19.25
3   25        1.0      1.0   1.0           57.20
4   35        0.0      1.0   1.0           19.25
5   49        1.0      0.0   0.0           57.20
6   68        1.0      1.0   1.0           57.20
7   71        1.0      0.0   0.0           57.20
8   73        1.0      0.0   1.0           57.20

A:

Using the np.bincount and the fact that gardening column is already 0 and 1
def grp_mean(bins, weights):
    counts = np.bincount(bins)
    sums = np.bincount(bins, weights)
    return (sums / counts)[bins]

ages.assign(avg_garden_age=grp_mean(ages.gardening.values.astype(int), ages.age))

   age  gardening  gameing  hats  avg_garden_age
0   13        0.0      1.0   1.0           19.25
1   14        0.0      1.0   0.0           19.25
2   15        0.0      1.0   0.0           19.25
3   25        1.0      1.0   1.0           57.20
4   35        0.0      1.0   1.0           19.25
5   49        1.0      0.0   0.0           57.20
6   68        1.0      1.0   1.0           57.20
7   71        1.0      0.0   0.0           57.20
8   73        1.0      0.0   1.0           57.20

