Here are my dataframe, function:
df = pd.DataFrame({
'G': 'x x y y'.split(),
'C': [1, 2, 1, 2],
'D': [2, 2, 1, 1]})
def CD(df):
return df['C'] * df['D']
Here is what my dataframe looks like:
G C D
0 x 1 2
1 x 2 2
2 y 1 1
3 y 2 1
When I run
df.groupby('G').apply(CD)
I expected that it would sum over x and y to get
G C D
0 x 3 4
1 y 3 2
Then, I expected it to multiply C and D to get
x 12
y 6
However, I got
G
x 0 2
1 4
y 2 1
3 2
That new column of [2, 4, 1, 2] doesn't look any different than what I would have obtained if I simply ran
df['C'] * df['D']
Clearly, I am confused about what groupby does. What is "df.groupby('G').apply(CD)" doing in my example?