0

In Python 3.11: to apply the square brackets operator to an object, the object's __getitem__ method should be implemented.

In Python's pandas module it is possible to apply square brackets to objects returned from a DataFrame by the groupby() method, e.g. tips.groupby("sex")["total_bill"].count(). (Example taken from this tutorial.)

However, there's no __getitem__ method listed in the pandas' API reference for GroupBy objects. How come? How is the square bracket operator implemented for pandas GroupBy objects?

Evan Aad
  • 5,699
  • 6
  • 25
  • 36
  • I don't think `__getitem__` is listed anywhere in most libraries. just like `__eq__` or `__le__`, these are Python default for corresponding ops and are not commonly listed in the docs. Instead, they're doc'ed by the ops. – Quang Hoang Aug 15 '23 at 14:32
  • @QuangHoang What do you mean by "doc'ed by the ops"? Where, in particular, is the pandas GroupBy square brackets operator documented? For instance, where is it document the type of object this operator returns? – Evan Aad Aug 15 '23 at 14:33
  • I'm not saying that Pandas doc lists the ops. I'm just saying you shouldn't be expecting the `__getitem__` is listed in the API. – Quang Hoang Aug 15 '23 at 14:38
  • @QuangHoang The `pandas` `GroupBy` API reference documents the `__iter__` methods. – Evan Aad Aug 15 '23 at 14:41

1 Answers1

1

Sometimes I use code like below to see the source if available:

import inspect
import pandas

groupby_obj = pandas.DataFrame().groupby(level=0)
print(f'{type(groupby_obj)=}\n{"-"*80}')

assert '__getitem__' in dir(groupby_obj)
code = inspect.getsource(groupby_obj.__getitem__)

print(code)

Or rather, I just type ?? after the functions to see the code in Jupyter Notebook. Anyway, you can definitely see __getitem__ in GroupBy object and read its source code.

As of mentioning __getitem__ in the pandas' API reference for GroupBy, I suppose that this part about selection in GroupBy was intended to explain how selection works in this case.

Vitalizzare
  • 4,496
  • 7
  • 13
  • 32