2

I have been working with pandas lately and of course used the .at[] and .loc[] accessors.

I don't ask how to use them.

I want to understand how they work and why they are not implemented as methods.

This might be a general Python topic that I dont know about. Feel free to refer to other threads. I searched but did not find anything useful.

Thanks in advance.

  • 2
    They call other methods behind the scenes, but I'd guess the decision of not making `loc` and `at` explicit methods is mainly for syntax sugar. In python, it would not be valid syntax to write the slice `:` as an argument to a method, for example `df.loc(:)` etc – rafaelc Aug 10 '19 at 17:55
  • Thanks. This actually makes sense. Do you know how to implement such "calling behind the scenes"? – ArsenieBoca Aug 10 '19 at 18:18

1 Answers1

1

As noted in the comments, .at[] and .loc[] are implemented as sliceable objects to allow slice syntax like .loc[3:5], which is not possible with methods (.loc(3:5)).

The way this is implemented in Python is by making at/loc return a custom object that implements __getitem__, like this:

class C(object):
  def __getitem__(self, val):
    print val

The logic inside __getitem__ can check the type of val passed and behave differently when passed, for example, a list (.loc[[False, False, False]]), a function (.loc[lambda x: ...]), or a slice object (.loc[3:5])

Nickolay
  • 31,095
  • 13
  • 107
  • 185