gpt4 book ai didi

python - Pandas:自定义类作为具有多索引的列标题

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:27 27 4
gpt4 key购买 nike

我正在尝试将对象用作多索引中的列标题数据框,但我似乎无法让它工作。 __eq__, __hash____str__ 只适用于简单的数据框。

这是一个小例子:

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'])

我还尝试实现 __le__、__ge____ne__。那没有做任何事。我真的不知道我还能做什么。有人有什么想法吗?

最佳答案

定义__lt____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

关于python - Pandas:自定义类作为具有多索引的列标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49563981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com