pandas groupby多功能 [英] pandas groupby multiple functions

查看:74
本文介绍了 pandas groupby多功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用EMP_NAME总结integer_transaction.

  1. 为什么我的第一个命令失败?如何修改
  2. 在第二条命令的情况下如何避免警告?
  3. 有什么方法可以将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

我要输出

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

推荐答案

尝试

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

          count  sum
EMP_NAME            
a             2    1
b             1    0

如果确实需要,可以使用其他.rename("count": "Frequency_count", "sum": "Frequency_sum")重命名列.

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

请注意如何引用count.

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

这篇关于 pandas groupby多功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆