【问题标题】:Pandas Index from objects来自对象的 Pandas 索引
【发布时间】:2013-11-26 18:24:33
【问题描述】:

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

看起来 contains 检查是在https://github.com/pydata/pandas/blob/master/pandas/index.pyx 第 92 和 448 行中定义的。

关于如何支持此类扩展列标签的任何想法?

【问题讨论】:

  • 这通常是不可能的。字符串需要是 c-hashable,IOW,执行索引计算的 c-lib 需要字符串。您可以尝试定义__hash__,可能会起作用。
  • 感谢杰夫的快速回复!

标签: python pandas


【解决方案1】:

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

【讨论】:

  • 优秀。这很有效,让 pandas 对我更加有用。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 2020-09-01
  • 2016-10-01
  • 2017-11-16
  • 2017-06-03
  • 2018-04-04
  • 1970-01-01
相关资源
最近更新 更多