Home > Back-end >  How to group by a variable in pandas
How to group by a variable in pandas

Time:09-27

I am trying to group by a variable in pandas, but it does not seem to work. The variable is just a list of several column headers, and it is much easier to write the variable each time for the purposes of analysis rather than list the columns for each groupby.

Trying to turn this:

df_grouped = (df.groupby(['Column1','Column2','Column3','Column4'])
        [compvars].sum()).reset_index()

Into this:

groupbyvars=['Column1','Column2','Column3','Column4']

df_grouped = (df.groupby([groupbyvars])
        [compvars].sum()).reset_index()

CodePudding user response:

As groupbyvars is already a list, we can replace :

df_grouped = (df.groupby([groupbyvars])
        [compvars].sum()).reset_index()

by :

df_grouped = (df.groupby(groupbyvars)
        [compvars].sum()).reset_index()
  • Related