Skip to main content
 首页 » 编程设计

python之简单分组的奇怪结果

2024年10月25日8zhoujg

下面的代码返回了我没有预料到的额外信息。这是个问题还是我遗漏了什么?

import pandas as pd 
df = pd.DataFrame({'symbol':['A','B','C'], 
                   'volume':[561,56,8]}) 
 
group = df.groupby('symbol') 
 
def f1(group): 
    print group 
    return group 
 
group.apply(f1) 

我得到:

  symbol  volume   
0      A     561   
  symbol  volume   
0      A     561   
  symbol  volume   
1      B      56   
  symbol  volume   
2      C       8   

如您所见,我的问题出在打印语句上。我得到了两次“A”组,我不确定这是否是一个错误。有人可以确认吗?

Pandas 版本:'0.14.1'

请您参考如下方法:

来自 Pandas documentation :

Warning: In the current implementation apply calls func twice on the first group 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 group.

这就是为什么您的方法在第一组中被调用一次的原因。这是通过实现。