-1

Suppose I have a data frame in Python as such;

varX varY varZ
01   A     34
01   B     26
02   A     18
02   B     50

How can I group this data frame by varX and take the sum of the third column(varZ) so that we can create a new data frame that looks like the following;

varX varZ
01   60
02   68

I already tried the following but it didn't work.

df_ = df.groupby(["varX"]).sum()

Any help is much appreciated. Thanks!

ipramusinto
  • 2,310
  • 2
  • 14
  • 24

1 Answers1

0

Try do sum for varZ column:

print(df.groupby("varX")['varZ'].sum())

Exactly what you want do as_index=False:

print(df.groupby("varX",as_index=False)['varZ'].sum())
U13-Forward
  • 69,221
  • 14
  • 89
  • 114