Ni_Tempe
Ni_Tempe

Reputation: 307

pandas groupby multiple functions

I want summarize the integer_transaction by EMP_NAME.

  1. why does my first command fail? How to modify it
  2. in case of the second command how to avoid the warning?
  3. Is there any way to put EMP_NAME in a column instead of the index

I want output

Emp_name Count Sum
a           2   1
b           1   0


import pandas as pd
import numpy as np
df = pd.DataFrame(data = {'EMP_NAME': ["a", "a", "b"], 'integer_transaction': [0, 1, 0]})

x=df.groupby(['EMP_NAME'])['integer_transaction'].agg({'Frequency_count': count, 'Frequency_Sum': np.sum})

x=df.groupby(['EMP_NAME'])['integer_transaction'].agg({'Frequency_count': np.size, 'Frequency_Sum': np.sum})

FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version
  # -*- coding: utf-8 -*-

Upvotes: 4

Views: 4923

Answers (1)

coffeinjunky
coffeinjunky

Reputation: 11514

Try

 df.groupby(['EMP_NAME'])['integer_transaction'].agg(["count", "sum"])

          count  sum
EMP_NAME            
a             2    1
b             1    0

If you really want, you can rename the columns using an additional .rename("count": "Frequency_count", "sum": "Frequency_sum").

Just for reference, the following also works perfectly fine:

x=df.groupby(['EMP_NAME'])['integer_transaction'].agg({'Frequency_count': "count", 'Frequency_Sum': np.sum})
x
__main__:1: FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version
Out[26]: 
          Frequency_count  Frequency_Sum
EMP_NAME                                
a                       2              1
b                       1              0

Note how count is quoted.

x=df.groupby(['EMP_NAME'])['integer_transaction'].agg({'Frequency_count': np.size, 'Frequency_Sum': np.sum})
x
__main__:1: FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version
Out[27]: 
          Frequency_count  Frequency_Sum
EMP_NAME                                
a                       2              1
b                       1              0

The warnings you get just tell you that this functionality will be removed in the future, so they should probably not be used. However, they do produce the correct answer.

To move the index to the column, try

df.groupby(['EMP_NAME'])['integer_transaction'].agg(["count", "sum"]).reset_index()
  EMP_NAME  count  sum
0        a      2    1
1        b      1    0

Upvotes: 6

Related Questions