将Pandas系列中的数字替换为布尔值

2024-06-28 18:57:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是一个玩具系列,用于说明目的

test = pd.Series([True, False, 2.2, 6.6, 0, True])

我有一个熊猫系列,包含真、假和一系列不同的数值。我想用False替换所有数字,这样整个列都是布尔值。我如何做到这一点? 我希望它的结局是:

0     True
1    False
2    False
3    False
4    False
5     True

谢谢


Tags: test目的falsetrue数字数值seriespd
3条回答

最简单的解决方案是通过True进行比较:

test = test == True
print (test)
0     True
1    False
2    False
3    False
4    False
5     True
dtype: bool

对于比较浮点和整数:

test = test.apply(lambda x: False if type(x) in (float, int) else x)
print (test)
0     True
1    False
2    False
3    False
4    False
5     True
dtype: bool

使用isinstance的解决方案:

def testing(x):
    if isinstance(x, bool):
        return x
    elif isinstance(x, (float, int)):
        return False
    else:
        return x

test = test.apply(testing)
print (test)
0     True
1    False
2    False
3    False
4    False
5     True
dtype: bool

这对浮动有效。我可以重复几遍。我相信还有更好的办法

df.col_1.apply(lambda x: False if type(x)==float else x)

试试这个:

>>> test[test!= True] = False
>>> test
0     True
1    False
2    False
3    False
4    False
5     True
dtype: object

相关问题 更多 >