Pandas: custom class as column header with multi indexing

只谈情不闲聊 提交于 2019-12-24 00:59:35

问题


I'm trying to use objects as column headers in a multi indexed dataframe but I can't seem to get it to work. __eq__, __hash__ and __str__ only work for simple data frames.

Here is a small example:

class Signal:

    def __init__(self, name):
        self.name = name


    def __eq__(self, other):
        try:
            return self.name == other or self.name == other.name
        except AttributeError as err:
            return False

    def __str__(self):
        return str(self.name)

    def __hash__(self):
        return hash(self.name)

if __name__ == '__main__':
    import pandas as pd
    import numpy as np
    a = Signal('name')
    b = Signal('name2')
    c = Signal('something')

    data = {
        ('A', a): np.arange(2),
        ('A', b): np.ones(2),
        ('B', c): np.zeros(2)
    }

    df = pd.DataFrame(data)

    print(df)
    print('-----------')
    print(df['A'])

I also tried implementing __le__, __ge__ and __ne__. That did not do anything though. I don't really have a clue what else I could do. Anybody got some ideas?


回答1:


After defining __lt__ and __gt__

class Signal:

    def __init__(self, name):
        self.name = name


    def __eq__(self, other):
        try:
            return self.name == other or self.name == other.name
        except AttributeError as err:
            return False

    def __lt__(self, other):
        return self.name < other.name

    def __gt__(self, other):
        return self.name > other.name

    def __str__(self):
        return str(self.name)

    def __hash__(self):
        return hash(self.name)

import pandas as pd
import numpy as np
a = Signal('name')
b = Signal('name2')
c = Signal('something')

data = {
    ('A', a): np.arange(2),
    ('A', b): np.ones(2),
    ('B', c): np.zeros(2)
}

df = pd.DataFrame(data)

print(df, df['A'], sep='\n\n')

     A               B
  name name2 something
0    0   1.0       0.0
1    1   1.0       0.0

   name  name2
0     0    1.0
1     1    1.0


来源:https://stackoverflow.com/questions/49563981/pandas-custom-class-as-column-header-with-multi-indexing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!