1

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

IE

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() 来获取不同函数中的第一次出现。

有没有办法检查一个对象的“真实性”来构造新的系列?

4

1 回答 1

1

不要使用==. 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>
于 2021-03-24T16:13:12.033 回答