Search code examples
pythonpandasdataframepandas-groupby

Can I use a specific element inside the groupby functions instead of using column name?


Im trying to use groupby function, is there a way to use a specific element rather than the column name. Example of code.

df.groupby(['Month', 'Place'])['Number'].sum()

This is what I want to do.

df.groupby(['April', Place'])['Number'].sum()

Solution

  • you need filter your DataFrame before:

    df.loc[df['Month'].eq('April')].groupby('Place')['Number'].sum()
    #df[df['Month'].eq('April')].groupby('Place')['Number'].sum()