Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 991
Semihcan Doken Avatar asked Oct 07 '17 01:10

Semihcan Doken


2 Answers

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.

like image 189
ZZB Avatar answered Oct 24 '22 16:10

ZZB


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

like image 22
EDToaster Avatar answered Oct 24 '22 16:10

EDToaster