这是出于说明目的的玩具系列。
test = pd.Series([True, False, 2.2, 6.6, 0, True])
我有一个Pandas系列,其中包含True,False和一堆不同的数值。我想用False替换所有数字,以便整个列都是布尔值。我该怎么做?我希望它最终像:
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
对于比较浮点数和整数:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句