Home > Software design >  Loop through list with columns does not work with groupby and aggregate function in Python Pandas?
Loop through list with columns does not work with groupby and aggregate function in Python Pandas?

Time:10-18

I have code in Python Pandas like below:

elements = ["col1", "col2", "col3"]
for el in elements:
    df.groupby(["xxx"]).agg({f"{el}" : sum})

As you can see, I try to group my DataFrame (df) by column "xxx" and the in loop aggregate some values from columns from list "elements" using function "sum".

Unfortunately above code does not generate result, where is the mistake ?

CodePudding user response:

You should probably just use:

out = df.groupby(['xxx'])[elements].sum()
  • Related