pandas groupby multiple functions

大城市里の小女人 提交于 2020-01-11 05:45:09

问题


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 -*-

回答1:


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


来源:https://stackoverflow.com/questions/50029927/pandas-groupby-multiple-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!