Skip to main content
 首页 » 编程设计

python之.apply 在 Pandas 中如何运作

2024年09月07日24jillzhang

我正在浏览 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.