为什么 pandas 申请两次计算 [英] Why does pandas apply calculate twice

查看:80
本文介绍了为什么 pandas 申请两次计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对熊猫的DataFrame对象使用apply方法.当我的DataFrame只有一列时,似乎应用的函数被调用了两次.问题是为什么?而且,我可以停止这种行为吗?

I'm using the apply method on a panda's DataFrame object. When my DataFrame has a single column, it appears that the applied function is being called twice. The questions are why? And, can I stop that behavior?

代码:

import pandas as pd

def mul2(x):
    print 'hello'
    return 2*x

df = pd.DataFrame({'a': [1,2,0.67,1.34]})

print df.apply(mul2)

输出:

hello
hello

0  2.00
1  4.00
2  1.34
3  2.68

我正在从所应用的函数中打印"hello".我知道它被应用了两次,因为"hello"打印了两次.更重要的是,如果我有两列,"hello"将打印3次.当我调用仅应用于"hello"列时,将打印4次.

I'm printing 'hello' from within the function being applied. I know it's being applied twice because 'hello' printed twice. What's more is that if I had two columns, 'hello' prints 3 times. Even more still is when I call applied to just the column 'hello' prints 4 times.

代码:

print df.a.apply(mul2)

输出:

hello
hello
hello
hello
0    2.00
1    4.00
2    1.34
3    2.68
Name: a, dtype: float64

推荐答案

可能与此问题.使用groupby时,应用函数将被额外调用一次,以查看是否可以进行某些优化.我猜这里正在发生类似的事情.目前看来还没有解决的办法(尽管我可能对您所看到的行为的来源有误).您是否有理由不进行额外的呼叫?

Probably related to this issue. With groupby, the applied function is called one extra time to see if certain optimizations can be done. I'd guess something similar is going on here. It doesn't look like there's any way around it at the moment (although I could be wrong about the source of the behavior you're seeing). Is there a reason you need it to not do that extra call.

此外,在您应用到该列时,调用它四次也是正常的.当您获得一列时,您将获得一个Series,而不是DataFrame.系列上的apply将功能应用于每个 元素.由于您的列中包含四个元素,因此该函数被调用了四次.

Also, calling it four times when you apply on the column is normal. When you get one columnm you get a Series, not a DataFrame. apply on a Series applies the function to each element. Since your column has four elements in it, the function is called four times.

这篇关于为什么 pandas 申请两次计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆