python - Pandas 对象索引

标签 python pandas

我希望能够在 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/

相关文章:

python - 在数据框中每行创建多个新行

python - Pandas 数据框每两行的组合

python - 将特定列从浮点转换为十进制

python - Python try/except取决于变量

python - 等到函数在 Python 中完成执行

python - 如何在 Django 中将开始 URL 与 REGEX 匹配

python - Pandas groupby,选择最大值的3个元素,并取每组的均值

python - 是否可以基于 Pandas 中的连接字符串创建数据框名称?

python - Oracle SQL 中的字符串匹配和表连接

python - 在 python 3 中使用 python 2 架子