如何为pd.DataFrame实现__missing__

时间:2017-01-26 17:42:39

标签: python oop pandas dataframe

我希望实现__missing__(与dict中相同的行为),而不会覆盖__getitem__的子类pandas.DataFrame。这是我到目前为止所尝试的:

import pandas as pd

class Bar0(pd.DataFrame):
    @property
    def _constructor(self):
        return Bar0


    def __missing__(self, key):
        print('Call __missing__ from {} with key'.format(type(self), key))
        return key


class Bar1(Bar0):
    @property
    def _constructor(self):
        return Bar1


    def __getitem__(self, key):
        print('Call __getitem__ from {} with key {}'.format(type(self), key))
        try:
            return super().__getitem__(key)
        except KeyError:
            return self.__missing__(key)


class Bar2(dict, Bar0):
    @property
    def _constructor(self):
        return Bar2


    def __init__(self, *args, **kwargs):
        Bar0.__init__(self, *args, **kwargs)
        dict.__init__(self)

        self.__getitem__ = Bar0.__getitem__


class Bar3(Bar0, dict):
    @property
    def _constructor(self):
        return Bar3


    def __init__(self, *args, **kwargs):
        Bar0.__init__(self, *args, **kwargs)
        dict.__init__(self)

        self.__getitem__ = Bar0.__getitem__

for bar in (Bar0, Bar1, Bar2, Bar3):
    foo = bar({'a': [1]})
    foo['a']
    try:
        foo['b']
    except KeyError:
        print('Raised KeyError for {}'.format(type(foo)))
    print('')

导致:

Raised KeyError for <class '__main__.Bar0'> // Didn't call __missing__

Call __getitem__ from <class '__main__.Bar1'> with key a
Call __getitem__ from <class '__main__.Bar1'> with key b // Did call __missing__ but also __getitem__ 
Call __missing__ from <class '__main__.Bar1'> with key

Call __missing__ from <class '__main__.Bar2'> with key // Didn't even find 'a' - I guess it searches __getitem__ from dict instead of pd.DataFrame
Call __missing__ from <class '__main__.Bar2'> with key

Raised KeyError for <class '__main__.Bar3'> // Didn't call __missing__

对于这个案件很重要:

  • Python:3.5
  • 熊猫:0.19.2 + 0.g825876c.dirty
  • OS:RHEL 6

0 个答案:

没有答案