我希望能够在 DataFrame 中包含列标签,它们是某些通用对象的实例。因此,用一个简单的类来包装 str 并提供一些附加功能,而不是 str 对象:
class WrapStr(object):
def __init__(self,str):
self.str = str
def __eq__(self,other):
return self.str == other.str
def __repr__(self):
return self.str
问题是 pd.Index 不会调用 WrapStr 实例上的 eq 方法,而只是检查两个实例是否相同。
first_ins = WrapStr('col1')
my_ix = pd.Index([first_ins])
sec_ins = WrapStr('col1')
print first_ins in my_ix # True
print sec_ins in my_ix # False
看起来包含检查是在 https://github.com/pydata/pandas/blob/master/pandas/index.pyx 中定义的第 92 行和 448 行。
关于如何支持此类扩展列标签有什么想法吗?
最佳答案
向 WrapStr
添加一个 __hash__
方法:
class WrapStr(object):
def __init__(self,str):
self.str = str
def __eq__(self,other):
return self.str == other.str
def __repr__(self):
return self.str
def __hash__(self):
return hash(self.str)
first_ins = WrapStr('col1')
my_ix = pd.Index([first_ins])
sec_ins = WrapStr('col1')
print first_ins in my_ix # True
print sec_ins in my_ix # False
关于python - Pandas 对象索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20195651/