Mar-14-2024, 06:12 PM
(This post was last modified: Mar-14-2024, 06:12 PM by deanhystad.)
The reason "df.loc(df["Date"] == date)" doesn't work is because that is not how you use loc. If you read the documentation you'll see that your second example is the correct syntax for using loc, other than the surrounding parenthesis that do nothing.
https://pandas.pydata.org/pandas-docs/st...e.loc.html
Are you looking for more explanation than "You are using it wrong"? I can take a shot.
DataFrame.loc is not a function, it is an object. In particular it is a _LocIndexer object. You can see that if you write something like this
There is another dunder method __call__ that gets called when you follow an instance by (). This is what happened in your first example. When you did this: df.loc(df["Date"] == date) you were actually doing this: df.loc.__call__(df["Date"] == date).
Your program crashed because you accidentally called loc.__call__() when you meant to call loc.__getitem__().
https://pandas.pydata.org/pandas-docs/st...e.loc.html
Are you looking for more explanation than "You are using it wrong"? I can take a shot.
DataFrame.loc is not a function, it is an object. In particular it is a _LocIndexer object. You can see that if you write something like this
import pandas as pd df = pd.DataFrame() print(df.loc)
Output:<pandas.core.indexing._LocIndexer object at 0x0000017ACE809030>
This class has a special method named __getitem__() that gets called when you use square brackets like this: df.loc[df.Date == date]. __getitem__() is one of many Python dunder methods (or magic methods) that are used to associate operators like [], >, + with methods __getitem__, __gt__, __add__.There is another dunder method __call__ that gets called when you follow an instance by (). This is what happened in your first example. When you did this: df.loc(df["Date"] == date) you were actually doing this: df.loc.__call__(df["Date"] == date).
Your program crashed because you accidentally called loc.__call__() when you meant to call loc.__getitem__().