gpt4 book ai didi

python - .apply 在 Pandas 中如何运作?

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:12 24 4
gpt4 key购买 nike

我正在浏览 this Ted Petrou 解释 .transform 和 .apply 之间区别的问题

这是使用的DataFrame

df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
'a':[4,5,1,3], 'b':[6,10,3,11]})

State a b
0 Texas 4 6
1 Texas 5 10
2 Florida 1 3
3 Florida 3 11

定义了函数inspect

def inspect(x):
print(x)

当我使用 apply 调用 inspect 函数时,我得到 3 个数据帧而不是 2 个

df.groupby('State').apply(lambda x:inspect(x))
State a b
2 Florida 1 3
3 Florida 3 11

State a b
2 Florida 1 3
3 Florida 3 11

State a b
0 Texas 4 6
1 Texas 5 10

为什么我在打印时得到 3 个数据帧,而不是 2 个?我真的很想知道 apply 函数是如何工作的?

提前致谢。

最佳答案

来自docs :

In the current implementation apply calls func twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first column/row.

关于python - .apply 在 Pandas 中如何运作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49403647/

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