python pandas 带括号和不带括号的函数

python pandas functions with and without parentheses

我注意到许多 DataFrame 函数如果不带括号使用似乎表现得像 'properties' 例如

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>

这是如何完成的?这是一种好的做法吗? 这是 pandas 0.15.1 在 linux

它们是不同的,不推荐,一个清楚地表明它是一种方法并且恰好输出结果而另一个显示预期的输出。

以下是您不应该这样做的原因:

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

好吧,你没有使用括号来正确调用该方法并看到一个看似有效的输出,但如果你引用了它并尝试使用它,那么你是在操作方法而不是 slice df 这不是你想要的。