Python 检查熊猫系列中数值的真实性

Python 检查熊猫系列中数值的真实性,python,pandas,numpy,boolean,truthiness,Python,Pandas,Numpy,Boolean,Truthiness,在pandas中,是否可以为使用自定义对象的索引构建布尔序列 i、 e 返回 True A 0 NaN 1 NaN 我想要的是 True A 0 False 1 True 或者类似的,以便我可以使用.first\u valid\u index()来获取不同函数中的第一个匹配项 有没有办法检查对象的“真实性”来构建新系列?不要使用==地图bool df.where(df['A'].map(bool))

在pandas中,是否可以为使用自定义对象的索引构建布尔序列

i、 e

返回

True
      A
0   NaN
1   NaN
我想要的是

True
        A
0   False
1    True
或者类似的,以便我可以使用.first\u valid\u index()来获取不同函数中的第一个匹配项


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

不要使用
==
<代码>地图
bool

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

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

但是,如果您定义了
\uuuuu eq\uuuu

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>
class Test():
定义初始化(self,num):
self.num=num
定义(自我):
return self.num==3
定义(自身、其他):
如果isinstance(其他,键入(自身)):
返回布尔(其他)=布尔(自身)
其他:
尝试:
返回类型(其他)(自身)=其他
除:
返回错误
x=测试(2)
y=试验(3)
df=pd.DataFrame({'A':[x,y]})
打印(bool(df['A'].iloc[1]))
打印(df.where(df['A']==True))
真的
A.
0南
1.

嗯,我理解你的担忧。这让我思考。但对我来说,它不会重现。哦!,这是因为它正在调用
其他
类型的
\uuu eq\uuu
。所以也许。。。是的<代码>y==y爆炸。接得好,我能做到。。。但我选择了另一条路。我从来没有想过使用
astype(bool)
,很高兴知道这一点。
df.where(df.astype(bool))

                                              A
0                                           NaN
1  <__main__.Test object at 0x000002A70187E6D0>
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>