Joining a Pandas series with a hierarchical index back to the source DataFrame

Viewed 943

I'm trying to wrap my brain around pandas data structures and trying to use them in anger a bit. I've figured out that groupby operations result in a pandas series object. But I can't quite figure out how to use the resulting series. In particular, I want to do two thing:

1) "join" the results back to the initial DataFrame

2) select a specific value from the resulting series based on the hierarchical index.

Here's a toy example to work with:

import pandas
df = pandas.DataFrame({'group1': ['a','a','a','b','b','b'],
                       'group2': ['c','c','d','d','d','e'],
                       'value1': [1.1,2,3,4,5,6],
                       'value2': [7.1,8,9,10,11,12]
})
dfGrouped = df.groupby( ["group1", "group2"] , sort=True)

## toy function, obviously not my real function
def fun(x): return mean(x**2)

results = dfGrouped.apply(lambda x: fun(x.value1))

so the resulting series (results) looks like this:

group1  group2
a       c          2.605
        d          9.000
b       d         20.500
        e         36.000

That makes sense. But how do I:

1) join this back to the original DataFrame df

2) Select a single value where, say, group1=='b' & group2=='d'

2 Answers
Related