Pandas 聚合错误(需要整数)

Pandas aggragation error (an integer is required)

df_act = pd.DataFrame({'A': {0: 'CHEMBL264', 1: 'CHEMBL4124', 2: 'CHEMBL264', 3: 'CHEMBL233', 4: 'CHEMBL233', 5: 'CHEMBL237', 6: 'CHEMBL236', 7: 'CHEMBL312', 8: 'CHEMBL3820', 9: 'CHEMBL3820'}, 'B': {0: 8.6999999999999993, 1: 8.1600000000000001, 2: 8.3000000000000007, 3: 7.2400000000000002, 4: 8.0, 5: 6.1600000000000001, 6: 6.4400000000000004, 7: 4.8200000000000003, 8: 7.5899999999999999, 9: 7.4299999999999997}})

这样做有效:

df_act.groupby(['A'])['B'].median()

但是,使用自定义函数将其应用于 groupby 对象失败:

def fun(x):
     name = {'B_median': x['B'].median()}
     return(pd.Series(names, index = ['B_median']))

df_act.groupby(['A'])['B'].apply(fun)

returns:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5126)()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:14010)()

TypeError: an integer is required

当然,在这两个示例中我使用的是相同的数据帧,所以我不明白这个错误。

编辑:添加 df_act 定义

问题是,在此示例中,您需要更改

df_act.groupby(['A'])['B'].apply(fun)

df_act.groupby(['A']).apply(fun)

中所详述,.apply的要点实际上是对每个"sub-DataFrame"(组)应用一个函数,然后将每个组的结果重新组合成你的结果。

在您的 fun 中,您已经在引用 'B'。所以事先对其进行索引是多余的。

另请注意,您实际上并不需要将返回的对象包装在系列中。它仍然有点做作,但这就足够了:

def fun(x):
     return x['B'].median()