6

I have a small question about the .plot() method in pandas.

So, let us say you have a dateframe saved into the variable: df. Let us say you wanted to make a bar chart about the data in the dataframe.

I know you can make the plot by calling df.plot(kind='bar'). Here, .plot() is a method of the df.

HOWEVER, you can also make the plot by calling df.plot.bar(). Here, .plot is an attribute of the df?

How is this possible that plot is both an attribute AND a method of the pandas df. I tried creating a class in python with an attribute and method having the same name, but the method overwrote the attribute. Does anyone know?

Zephyr
  • 11,891
  • 53
  • 45
  • 80
varun413
  • 141
  • 6
  • 1
    There's a `__call__` that allows calling a class as a function. See, for example, [this link](https://www.geeksforgeeks.org/__call__-in-python/). – Quang Hoang Aug 11 '20 at 21:26
  • See [Source: panda.DataFrame.plot](https://github.com/pandas-dev/pandas/blob/v1.1.0/pandas/plotting/_core.py#L607-L1702) and [Source: pandas.DataFrame.plot.bar](https://github.com/pandas-dev/pandas/blob/v1.1.0/pandas/plotting/_core.py#L1019-L1107). – Trenton McKinney Aug 11 '20 at 21:35
  • THANKS Quang, i just wrote a function that did exactly what my question asked using what you said and it worked! It appears that .plot is an attribute of a pandas df, and calling it creates a plotting class which has a method .bar() OR you can simply call the class using __call__ – varun413 Aug 11 '20 at 23:06
  • Does this answer your question? [What is the difference between \_\_init\_\_ and \_\_call\_\_?](https://stackoverflow.com/questions/9663562/what-is-the-difference-between-init-and-call) – Gonçalo Peres May 05 '21 at 08:54

0 Answers0