带有和不带有括号的python pandas函数 [英] python pandas functions with and without parentheses

查看:314
本文介绍了带有和不带有括号的python pandas函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果使用许多不带括号的DataFrame函数,其行为似乎类似于属性".

I notice that many DataFrame functions if used without parentheses seem to behave like 'properties' e.g.

In [200]: df = DataFrame (np.random.randn (7,2))

In [201]: df.head ()
Out[201]: 
      0         1
   0 -1.325883  0.878198
   1  0.588264 -2.033421
   2 -0.554993 -0.217938
   3 -0.777936  2.217457
   4  0.875371  1.918693

In [202]: df.head 
Out[202]: 
<bound method DataFrame.head of           0         1
   0 -1.325883  0.878198
   1  0.588264 -2.033421
   2 -0.554993 -0.217938
   3 -0.777936  2.217457
   4  0.875371  1.918693
   5  0.940440 -2.279781
   6  1.152370 -2.733546>

这是如何完成的,这是一种好的做法吗? 这是Linux上的熊猫0.15.1

How is this done and is it good practice ? This is with pandas 0.15.1 on linux

推荐答案

它们是不同的,不建议使用,一个清楚地表明这是一种方法,恰好输出结果,而另一个则显示了预期的输出.

They are different and not recommended, one clearly shows that it's a method and happens to output the results whilst the other shows the expected output.

这就是为什么您不应该这样做:

Here's why you should not do this:

In [23]:

t = df.head
In [24]:

t.iloc[0]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-b523e5ce509d> in <module>()
----> 1 t.iloc[0]

AttributeError: 'function' object has no attribute 'iloc'

In [25]:

t = df.head()
t.iloc[0]
Out[25]:
0    0.712635
1    0.363903
Name: 0, dtype: float64

好吧,您不能使用括号正确地调用该方法并看到显示为有效的输出,但是如果您引用了该引用并尝试使用它,那么您将对方法进行操作,而不是对df的切片进行操作这不是您想要的.

So OK you don't use parentheses to call the method correctly and see an output that appears valid but if you took a reference to this and tried to use it, you are operating on the method rather than the slice of the df which is not what you intended.

这篇关于带有和不带有括号的python pandas函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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