我有一个包含 2 列 nbr 和标签的数据框。 Nbr 包含整数,tag 包含 Tag 对象。
我想获取所有标签对象的平均值(使用 value 属性,结果是具有该值的新标签)。
对于 dataframe.add我添加了 __add__ Tag 类的方法。 示例:
import pandas as pd
class Tag(object):
def __init__(self, value):
self.value = value
def __add__(self, other):
return Tag(self.value + other.value)
a = Tag(2)
b = Tag(8)
frame = pd.DataFrame({
'tag': [a, b],
'nbr': [3, 6]
})
new_tag = frame.tag.sum()
print new_tag.value # 10
但对于 frame.tag.mean()我收到此错误 TypeError: Could not convert <__main__.Tag object at 0x7f375ac460d0> to numeric . Pandas 首先尝试将对象转换为 float :float(x) ,然后如果它失败了,试试这个:x = complex(x) .
我的问题是他们如何制作float(tag_object)或 complex(tag_object)像我对 __add__ 所做的那样,通过向我的 Tag 类添加一个方法来返回值属性?
提前致谢。
请您参考如下方法:
查看源代码,似乎 Pandas 的 mean 将结果强制转换为数字类型。
您可以通过添加 special __float__ method 来关闭到标签:
import pandas as pd
class Tag(object):
def __init__(self, value):
self.value = value
def __add__(self, other):
return Tag(self.value + other.value)
def __float__(self):
return float(self.value)
一旦你这样做了,你就得到了
a = Tag(2)
b = Tag(8)
frame = pd.DataFrame({
'tag': [a, b],
'nbr': [3, 6]
})
new_tag = frame.tag.mean()
>>> print(new_tag)
5.0
请注意,这并不完全符合您的要求(它不会创建值为 5.0 的 Tag - Pandas 希望结果为数字类型)。
