鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python/ pandas中使用groupby之后進行apply為什么結(jié)果會多出一個輸出?

pandas中使用groupby之后進行apply為什么結(jié)果會多出一個輸出?

df = pd.DataFrame([[4, 9],[4, 2], [4, 5], [5, 4]], columns=['A', 'B'])
df.groupby(['A']).apply(lambda x : print(x, '\n'))

df為:

  A  B
0  4  9
1  4  2
2  4  5
3  5  4

使用apply之后輸出結(jié)果如下:


       A  B
    0  4  9
    1  4  2
    2  4  5 
    
       A  B
    0  4  9
    1  4  2
    2  4  5 
    
       A  B
    3  5  4 

請問為什么會重復出現(xiàn),不是最后應該只有兩個分組嗎

       A  B
    0  4  9
    1  4  2
    2  4  5 
回答
編輯回答
蟲児飛
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.

refer: http://pandas.pydata.org/pand...

2017年2月26日 09:31