Python 如何为pd.DataFrame实现_缺失_
我想实现Python 如何为pd.DataFrame实现_缺失_,python,oop,pandas,dataframe,Python,Oop,Pandas,Dataframe,我想实现\uuuuu missing\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu(与dict中的行为相同),而不覆盖pandas.DataFrame的子类。以下是我迄今为止所做的尝试: import pandas as pd class Bar0(pd.DataFrame): @property def _constructor(self): return Bar0 def __missing
\uuuuu missing\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
(与dict
中的行为相同),而不覆盖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__
<代码>为//引发了KeyError,但未调用\uu__
使用键a从调用
使用键b从调用uuu getitem//Did Call uuu missing uuuuuuu,但也uuu getitem uuu
用键从中调用“缺少”
使用键//调用uuu missing uuuuuuuuuuuuu from甚至没有找到“a”-我猜它从dict而不是pd.DataFrame搜索uuuu getitem
用键从中调用“缺少”
//的引发键错误未调用\u\u丢失__
对于重要的情况:
- Python:3.5
- 熊猫:0.19.2+0.g825876c
- 操作系统:RHEL 6
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
特别是目录中的内容。这不是一般的事情。分配给self.\uu getitem\uu
对索引操作没有影响。还有,\u构造函数
应该是什么?Python不会调用其构造函数\u constructor
@user2357112,thx以获取您的评论。关于\u构造器
(),似乎您的设计是正确的。我仍然对分配属性和定义属性的区别感到困惑。因为我假设方法本身只是一个指向函数的函数指针属性。看起来构造函数确实是一个可以识别的东西。谷歌没有找到它,因为谷歌不喜欢符号。至于分配给self.\uuuuu getitem\uuuuu
,Python在执行特殊方法查找时跳过实例dict,因此它跳过实例dict中的\uuuu getitem\uuuuuuu
项<代码>\uuuu缺失\uuuu
在这里是一个危险的话题。