Why does `head` need `()` and `shape` does not?

二次信任 提交于 2020-12-29 07:18:05

问题


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. 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?

  2. 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?


回答1:


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.




回答2:


When you call data.head() you are calling the method head(self) on the object data,

However, when you write data.shape, you are referencing a public attribute of the object data

It is good to keep in mind that there is a distinct difference between methods and object attributes. You can read up on it here



来源:https://stackoverflow.com/questions/46615919/why-does-head-need-and-shape-does-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!