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

标签 python pandas

我注意到许多 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 的切片这不是你想要的。

关于python pandas 带括号和不带括号的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27980843/

相关文章:

带有字符串的 Python Pandas Dataframe 插值

python - 软删除 Django 数据库对象

python - 类型错误 : 'NoneType' object has no attribute '__getitem__' tkinter error

python - Pandas :列之间的差异

python - 如何在 matplotlib 条形图中添加颜色?

python - Pandas 滚动但涉及最后一行值

python - 如何重命名 pandas 数据框中的条目?

python - 为什么 Python 会删除字符串的最后一个字符?

python - 分割数据帧的行并将它们作为单独的行存储在同一数据帧中

python - IOError : [Errno 24] Too many open files: