2

I have the following dataframe:

df.index = df['Date']
df.groupby([df.index.month, df['Category'])['Amount'].sum()

Date   Category     Amount     
1      A            -125.35
       B            -40.00
                    ...
12     A            505.15
       B            -209.00

I would like to report the sum of the Amount for every Category B like:

Date   Category     Amount     
1      B            -40.00
                    ...
12     B            -209.00

I tried the df.get_group method but this method needs tuple that contains the Date and Category key. Is there a way to filter out only the Categories with B?

5
  • df.query('Category == "B"').groupby([df.index.month, df['Category'])['Amount'].sum() ? Commented May 28, 2020 at 20:36
  • This results in an Error: ValueError: Grouper and axis must be same length Commented May 28, 2020 at 20:47
  • df.query('Category == "B"').groupby([df['Date'].dt.month, df['Category'])['Amount'].sum(), now you can also skip your line of settings the new index Commented May 28, 2020 at 20:48
  • Alright but I still get the same error message Commented May 28, 2020 at 20:56
  • I see, it's becaue df['Date'].dt.month points to original index. Try cat_b = df.query('Category == "B"') Then after that cat_b.groupby([cat_b.dt.month, 'Category'])['Amount'].sum() Commented May 28, 2020 at 20:58

2 Answers 2

3

You can use IndexSlice:

# groupby here
df_group = df.groupby([df.index.month, df['Category'])['Amount'].sum()

# report only Category B
df_group.loc[pd.IndexSlice[:,'B'],:]

Or query:

# query works with index level name too
df_group.query('Category=="B"')

Output:

               Amount
Date Category        
1    B          -40.0
12   B         -209.0
Sign up to request clarification or add additional context in comments.

Comments

0

apply a filter to your groupby dataframe where Category equals B

filter=df['Category']=='B'
df[filter].groupby([df.index.month, df['Category'])['Amount'].sum()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.