gpt4 book ai didi

python - 我们如何将函数应用于 pandas 和 python 中的整个组?

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:03 24 4
gpt4 key购买 nike

我们如何将函数应用于 python 中的 pandas dataframe 中的整个组?这是我到目前为止的代码:

df_grouped = df.groupby(['key1', 'key2'])
result_with_bla = df_grouped.magic_apply(myfunc)

基本上我想要一个 magic_apply 函数,它在 df_grouped 的每个子组上调用 myfunc,而不是在每一行上。存在吗?

最佳答案

正如 @DSM 指出的那样,“魔法应用”简称为... apply 。这是一个 groupby 方法:

In [11]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])

In [12]: g = df.groupby(['A'])

In [13]: def f(x):
print(x)
return len(x)

In [14]: g.apply(f)
A B
0 1 2
1 1 4

A B
0 1 2
1 1 4

A B
2 5 6
Out[14]:
A
1 2
5 1
dtype: int64

注意:令人困惑的是,即使只有两个组,f 也被应用了 3 次 - 这是因为 pandas 需要确定返回类型。

关于python - 我们如何将函数应用于 pandas 和 python 中的整个组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510447/

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