这是一个用于说明目的的玩具系列。
test = pd.Series([True, False, 2.2, 6.6, 0, True])
我有一个包含 True、False 和一堆不同数值的 Pandas 系列。我想用 False 替换所有数字,以便整个列都是 bool 值。我该如何做到这一点? 我希望它最终像这样:
0 True
1 False
2 False
3 False
4 False
5 True
谢谢!
请您参考如下方法:
最简单的解决方案是通过 True 进行比较:
test = test == True
print (test)
0 True
1 False
2 False
3 False
4 False
5 True
dtype: bool
比较 float 和整数:
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
