Is loc[ ] a function in Pandas

不羁的心 提交于 2021-02-11 12:50:19

问题


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?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/66043313/is-loc-a-function-in-pandas

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