What are the types of loc and iloc? (brackets and parentheses)

I am from C ++ and started to learn python recently. I studied indexing and data selection. I met .iloc[] in the Series , DataFrame and Panel classes in the pandas library. I could not understand what .iloc ? Is this a function or attribute? Many times I mistakenly use () instead of [] and do not get the actual result (but it does not cause me an error).

Example:

 In [43]: s = pd.Series(np.arange(5), index=np.arange(5)[::-1], dtype='int64') In [44]: s[s.index.isin([2, 4, 6])] Out[44]: 4 0 2 2 dtype: int64 In [45]: s.iloc(s.index.isin([2,4,6])) Out[45]: <pandas.core.indexing._iLocIndexer at 0x7f1e68d53978> In [46]: s.iloc[s.index.isin([2,4,6])] Out[46]: 4 0 2 2 dtype: int64 

Can someone tell me a link where it is better to study these types of operators.

+5
source share
2 answers

The practical answer:. You should think of iloc and loc as pandas extensions of the python list and dictionary, respectively, and treat them as search queries, not function or method calls. Thus, observing the python syntax, always use [] , not () .

 >>> ser = pd.Series( { 'a':3, 'c':9 } ) >>> ser.loc['a'] # pandas dictionary syntax (label-based) 3 >>> ser.iloc[0] # pandas list/array syntax (location-based) 3 

This is basically the same for dataframes, just with an extra dimension to indicate, and also where iloc and loc become more useful, but beyond the scope of this question.

Deeper answer: If you are really trying to understand this at a deeper level, you need to understand __getitem__ . Perhaps you can start here for some basics. The answers in the second link given in the comments above by @ayhan are also great for your question.

+4
source

.iloc is an instance of a class.

 pd.DataFrame().iloc Out[2]: <pandas.core.indexing._iLocIndexer at 0x97a2470> 

Source: Pandas Source Code - indexing.py#L1626

+3
source

Source: https://habr.com/ru/post/1269060/


All Articles