gpt4 book ai didi

python - Pandas 聚合错误(需要整数)

转载 作者:行者123 更新时间:2023-12-01 02:23:03 25 4
gpt4 key购买 nike

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)

返回:

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

详情请参阅 How is pandas groupby method actually working?.apply 的要点实际上是将函数应用于每个“子 DataFrame”(组),然后将每个组的结果重新组合到您的结果中。

在您的fun中,您已经引用了“B”。因此预先对其建立索引是多余的。

这里还要注意,您实际上并不需要将返回的对象包装在 Series 中。虽然还是有点做作,但这就足够了:

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

关于python - Pandas 聚合错误(需要整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47755844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com