I have defined a custom class in Python as a dictionary of dataframes:
class DictOfDF(dict):
__slots__ = ()
def __init__(self, *args, **kwargs):
super(DictOfDF, self).__init__(*args, **kwargs)
def __getitem__(self, key):
return super(DictOfDF, self).__getitem__(key)
def __setitem__(self, key, value):
return super(DictOfDF, self).__setitem__(key, value)
def __delitem__(self, key):
return super(DictOfDF, self).__delitem__(key)
def get(self, key, default=None):
return super(DictOfDF, self).get(key, default)
def setdefault(self, key, default=None):
return super(DictOfDF, self).setdefault(key, default)
def pop(self, key, value):
return super(DictOfDF, self).pop(key, value)
def update(self, *args, **kwargs):
super(DictOfDF, self).update(*args, **kwargs)
def __contains__(self, key):
return super(DictOfDF, self).__contains__(key)
def copy(self):
return type(self)(self)
def __repr__(self):
return '{0}({1})'.format(type(self).__name__, super(DictOfDF, self).__repr__())
To avoid a discussion of whether or not subclassing from dict is preferable to subclassing from UserDict etc., note that the above is inspired by the answer here: https://stackoverflow.com/a/39375731/19682557
I want to define a 'loc' property for this DictOfDF class such that:
import pandas as pd
import datetime as dt
class DictOfDF(dict):
...
x = DictOfDF({'x1': pd.DataFrame(np.nan, index=pd.date_range(dt.datetime(2000, 1, 1), dt.datetime(2000, 12, 31)),
columns=['a', 'b', 'c']),
'x2': pd.DataFrame(np.nan, index=pd.date_range(dt.datetime(2000, 1, 1), dt.datetime(2000, 12, 31)),
columns=['a', 'b', 'c'])})
# x.loc['2000-03':'2000-04',['a','b']] should return a DictOfDF whose two dataframes are subsetted to the date range 2000-03/2000-04 and columns 'a' and 'b'
My idea would be to add a property like the following to the class definition, however this doesn't seem to work
class DictOfDF(dict):
...
@property
def loc(self):
return DictOfDF({key: value._LocIndexer for key, value in self.items()})
I get the error
AttributeError: 'DataFrame' object has no attribute '_LocIndexer'
I feel that I am on the right track, but any suggestions for fixing this would be much appreciated. Knowing how to define a similar 'iloc' property would also be useful, in case the custom implementation of this is materially different to 'loc'.