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

2023-12-10

我注意到许多 DataFrame 函数如果不带括号使用似乎表现得像“属性”,例如

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 上的 pandas 0.15.1


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

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

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 的切片,而该切片不是你的意图是什么。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python pandas 带括号和不带括号的函数 的相关文章

随机推荐