2024-06-28 18:57:13 发布
网友
这里是一个玩具系列,用于说明目的
test = pd.Series([True, False, 2.2, 6.6, 0, True])
我有一个熊猫系列,包含真、假和一系列不同的数值。我想用False替换所有数字,这样整个列都是布尔值。我如何做到这一点? 我希望它的结局是:
0 True 1 False 2 False 3 False 4 False 5 True
谢谢
最简单的解决方案是通过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的解决方案:
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
最简单的解决方案是通过
True
进行比较:对于比较浮点和整数:
使用
isinstance
的解决方案:这对浮动有效。我可以重复几遍。我相信还有更好的办法
试试这个:
相关问题 更多 >
编程相关推荐