为什么`head` 需要`()` 而`shape` 不需要? [英] Why does `head` need `()` and `shape` does not?

查看:65
本文介绍了为什么`head` 需要`()` 而`shape` 不需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我将一个 csv 文件导入 Python 的 Pandas 库并显示前 5 行,并查询 Pandas 数据框的形状".

In the following code, I import a csv file into Python's pandas library and display the first 5 rows, and query the 'shape' of the pandas dataframe.

import pandas as pd
data = pd.read_csv('my_file.csv')
data.head() #returns the first 5 rows of the dataframe
data.shape  # displays the # of rows and # of columns of dataframe

  1. 为什么head()方法在head之后需要空括号,但是shape才不是?这与他们的类型有关吗?如果我调用 head 而不用空括号跟随它,我不会得到相同的结果.难道 head 是一个方法而 shape 只是一个属性?

  1. Why is it that the head() method requires empty parentheses after head but shape does not? Does it have to do with their types? If I called head without following it with the empty parentheses, I would not get the same result. Is it that head is a method and shape is just an attribute?

我如何将上述问题的答案推广到 Python 的其余部分?我在这里不仅要学习大熊猫,还要学习 Python.例如,诸如当 _____ 是这种情况时,如果不提供任何参数,则必须包含空括号,但对于其他属性则不必?

How could I generalize the answer to the above question to the rest of Python? I am trying to learn not just about pandas here but Python in general. For example, a sentence such as "When _____ is the case, one must include empty parentheses if no arguments will be provided, but for other attributes one does not have to?

推荐答案

head 是方法而不是属性的原因很可能与性能有关.如果 head 是一个属性,则意味着每次您处理数据帧时,pandas 都必须预先计算数据切片并将其存储在 head 属性中,这将浪费资源.其他带有空括号的方法也是如此.

The reason that head is a method and not a attribute is most likely has to do with performance. In case head would be an attribute it would mean that every time you wrangle a dataframe, pandas would have to precompute the slice of data and store it in the head attribute, which would be waste of resources. The same goes for the other methods with empty parenthesis.

在形状的情况下,它作为属性提供,因为此信息对于任何数据帧操作都是必不可少的,因此它是预先计算的并可作为属性使用.

In case of shape, it is provided as an attribute since this information is essential to any dataframe manipulation thus it is precomputed and available as an attribute.

这篇关于为什么`head` 需要`()` 而`shape` 不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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