python - groupby apply 函数不能处理多个函数

标签 python pandas

我有这个数据农场:

df = pd.DataFrame(
    {'cn':[1,1,1,1,2,2,2], 'date': ['01/10/2017', '02/09/2016', '02/10/2016','01/20/2017', '05/15/2017', '02/10/2016', '02/10/2018'],
     'score':[4,10,6, 5, 15, 7, 8]})

    cn  date    score
0   1   01/10/2017  4
1   1   02/09/2016  10
2   1   02/10/2016  6
3   1   01/20/2017  5
4   2   05/15/2017  15
5   2   02/10/2016  7
6   2   02/10/2018  8

我有这两个功能:

def total_count_phq9_BOF_activation (grf):
    s = grf.score.count()
    return s

def first_phq9_BOF_activation (grf):
    value =grf[grf.score==grf.score.max()].date
    return value

我使用此解决方案(1)将这两个函数用于 apply 方法:

df.groupby('cn').apply (lambda x: pd.Series({"first_phq9_BOF_activation": first_phq9_BOF_activation , "total_count_phq9_BOF_activation": total_count_phq9_BOF_activation}))

但是没有成功。您能让我知道我的代码的哪一部分是错误的吗?

Apply multiple functions to multiple groupby columns

最佳答案

您没有在 Series 构造函数内调用函数 total_count_phq9_BOF_activationfirst_phq9_BOF_activation。它们不是 apply 的一部分。它们属于系列构造函数,因此您需要使用 (x)

专门调用它们
df.groupby('cn').apply (lambda x: pd.Series({"first_phq9_BOF_activation": first_phq9_BOF_activation(x) , 
                                             "total_count_phq9_BOF_activation": total_count_phq9_BOF_activation(x)}))

Out[157]:
                    first_phq9_BOF_activation  total_count_phq9_BOF_activation
cn
1   1    02/09/2016
Name: date, dtype: object                                4
2   4    05/15/2017
Name: date, dtype: object                                3

关于python - groupby apply 函数不能处理多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828391/

相关文章:

python - 无法将一些难以辨认的内容处理为可读

Python StructuredProperty 到字典

python - pip : command in environment . yaml 文件的含义是什么?

python - 在 pandas 数据框中重新排序数据

python - 如何在考虑行子集的同时遍历 Pandas DataFrame

python - 嵌套变量创建

python - Pandas 蟒 : Merging every two rows in one dataframe

pandas - XLRDError : Unsupported format, 或损坏的文件

python - 保留完整姓氏,在 pandas 列中获取名字的首字母(如果有的话,还有中间名)

python - 如何根据列中值的差异拆分 Pandas 数据框