What is the alternative to pandas chain indexing?

I take an online class to learn python, and the teacher taught us that indexing the chain was not a good idea. However, he could not say that this is a suitable alternative for use.

Suppose I have a Pandas data frame with rows indexed as ['1', '2', '3'] and columns named ['a', 'b', 'c'] .

What is the appropriate alternative to using the df['1']['a'] command to retrieve the value found in the first row and first column?

+5
source share
1 answer

Use multi-axis indexing like

 df.loc['a', '1'] 

When you use df['1']['a'] , you first access the series object s = df['1'] , and then access the series element s['a'] , resulting in two calls to __getitem__ , both of which are heavily overloaded (handle a lot of scenarios such as slicing, indexing a boolean mask, etc.).

It is much more efficient to use the df.loc indexer.

+6
source

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


All Articles