检查 Pandas 系列中值的真实性

问题描述

在 Pandas 中,是否可以构建一个布尔序列来使用自定义对象进行索引?

class test():
    def __init__(self,num):
        self.num = num
    def __bool__(self):
        return self.num == 3

x = Test(2)
y = Test(3)

df = pd.DataFrame({'A':[x,y]})

print(bool(df['A'].iloc[1]))
print(df.where(df['A'] == True))

返回

True
      A
0   NaN
1   NaN

我想要的是这样的

True
        A
0   False
1    True

或类似的,以便我可以使用 .first_valid_index() 来获取不同函数中的第一次出现。

有什么方法可以检查对象的“真实性”以构建新系列吗?

解决方法

不要使用==map bool 代替

df.where(df['A'].map(bool))

                                              A
0                                           NaN
1  <__main__.Test object at 0x000002A70187E6D0>

astype(bool)

df.where(df.astype(bool))

                                              A
0                                           NaN
1  <__main__.Test object at 0x000002A70187E6D0>

但是,如果您定义一个 __eq__

class Test():
    def __init__(self,num):
        self.num = num
    def __bool__(self):
        return self.num == 3
    def __eq__(self,other):
        if isinstance(other,type(self)):
            return bool(other) == bool(self)
        else:
            try:
                return type(other)(self) == other
            except:
                return False


x = Test(2)
y = Test(3)

df = pd.DataFrame({'A':[x,y]})

print(bool(df['A'].iloc[1]))
print(df.where(df['A'] == True))

True
                                              A
0                                           NaN
1  <__main__.Test object at 0x000002A701897520>