df.head()和df.head有什么区别?

5
在Jupyter Notebook或终端中,df.head和df.head()都可以返回数据框的输出,但有一些细微的差别。这两种不同表达式的根本区别是什么?括号在Python中起着什么作用呢?
谢谢!
>>>df.head
<bound method NDFrame.head of          Date    Open    High     Low   Close    Volume
0    1-Jun-17  153.17  153.33  152.22  153.18  16404088
1    2-Jun-17  153.58  155.45  152.89  155.45  27770715
2    5-Jun-17  154.34  154.45  153.46  153.93  25331662
3    6-Jun-17  153.90  155.81  153.78  154.45  26624926
4    7-Jun-17  155.02  155.98  154.48  155.37  21069647
5    8-Jun-17  155.25  155.54  154.40  154.99  21250798
6    9-Jun-17  155.19  155.19  146.02  148.98  64882657
7   12-Jun-17  145.74  146.09  142.51  145.42  72307330
8   13-Jun-17  147.16  147.45  145.15  146.59  34165445
9   14-Jun-17  147.50  147.50  143.84  145.16  31531232
10  15-Jun-17  143.32  144.48  142.21  144.29  32165373
>>> df.head()
       Date    Open    High     Low   Close    Volume
0  1-Jun-17  153.17  153.33  152.22  153.18  16404088
1  2-Jun-17  153.58  155.45  152.89  155.45  27770715
2  5-Jun-17  154.34  154.45  153.46  153.93  25331662
3  6-Jun-17  153.90  155.81  153.78  154.45  26624926
4  7-Jun-17  155.02  155.98  154.48  155.37  21069647
3个回答

10

那些可不只是“微小的差异”。你根本没有使用 df.head 来获取表头。

df.head() 会真正获取数据框的表头。你可以看到输出结果只有5行:

>>> df.head()
       Date    Open    High     Low   Close    Volume
0  1-Jun-17  153.17  153.33  152.22  153.18  16404088
1  2-Jun-17  153.58  155.45  152.89  155.45  27770715
2  5-Jun-17  154.34  154.45  153.46  153.93  25331662
3  6-Jun-17  153.90  155.81  153.78  154.45  26624926
4  7-Jun-17  155.02  155.98  154.48  155.37  21069647

相比之下,df.head 只是数据框 df 的方法 head 的方法对象。需要使用括号来实际调用该方法。方法对象的 repr 基本上是

f"<bound method {classname}.{methodname} of {object!r}"

将类名、方法名和对象的repr替换为相应的位置。看起来像数据框的输出部分实际上是原始dfrepr。 它有10行而不是5行,因为它是整个原始数据帧,而不是头部。


5

head 返回一个方法,head() 返回数据框中前5行(默认)的数据。

type(df.head)
<class 'method'>
type(df.head())
<class 'pandas.core.frame.DataFrame'>

-1

括号用于调用函数。让我们以一个小例子来说明,使用append而不带括号在列表上将什么也不做,因为它只会返回函数本身,但是使用括号调用函数:

a = [1]
a.append
print(a)
[1]

a.append(2)
print(a)
[1, 2]

append = a.append
append(3)
print(a)
[1, 2, 3]

当你只使用head时,看到的内容是类似的。他们只是添加了一些代码来实际调用带有默认值的函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接