Normal syntax for calling a function is func() but I have noticed that loc[] in pandas is without parentheses and still treated as a function. Is loc [] really a function in pandas?
-
1Does this answer your question? [Why/How does Pandas use square brackets with .loc and .iloc?](https://stackoverflow.com/questions/46176656/why-how-does-pandas-use-square-brackets-with-loc-and-iloc) – user202729 Feb 04 '21 at 10:01
-
The [question](https://stackoverflow.com/questions/46176656/why-how-does-pandas-use-square-brackets-with-loc-and-iloc) linked by @user202729 (that was closed and not answered) wasn't a duplicate. Now that it was reopened, however, I added an answer there that includes my answer here and goes more into depth on the "why" this syntax is used. @ OP would you consider taking a look at the *other* question and see if this might be considered a duplicate now? – GPhilo Feb 04 '21 at 10:56
3 Answers
Is loc[ ] a function in Pandas?
No. The simplest way to check is:
import pandas as pd
df = pd.DataFrame()
print(df.loc.__class__)
which prints
<class 'pandas.core.indexing._LocIndexer'>
this tells us that df.loc
is an instance of a _LocIndexer
class. The syntax loc[]
derives from the fact that _LocIndexer
defines __getitem__
and __setitem__
*, which are the methods python calls whenever you use the square brackets syntax.
*Technically, it's its base class _LocationIndexer
that defines those methods, I'm simplifying a bit here

- 18,519
- 9
- 63
- 89
LOC[] is a property that allows Pandas to query data within a dataframe in a standard format. Basically you're providing the index of the data you want.

- 1
- 3
-
*"Basically you're providing the address of the data you want."*.. no, you're not providing any address. At best, you're providing the *index* of the data you want, but that's also not answering the question of "how does this work" – GPhilo Feb 04 '21 at 10:10
Create a simple DataFrame df
and look at the type of df.loc:
>>> type(df.loc)
pandas.core.indexing._LocIndexer
This means calling loc
on a DataFrame returns an object of the type _LocIndexer
, so .loc
is not a function or method.
Look at what happens when we inspect the type of an actual function / method of a DataFrame:
>>> type(df.rename)
method
So what really happens here, is that you are accessing an attribute of your DataFrame called loc
, which contains an object of type _LocIndexer
, which itself implements the dunder methods __getitem__
. This is a magic method that can be implemented by an object in order to define what happens when the object is indexed with the square bracket notation, just like a list or a dictionary.

- 1,844
- 1
- 6
- 13