用布尔值替换 Pandas 系列中的数字
Replace Numerics in Pandas Series with Boolean
这里有一个玩具系列供说明之用。
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
谢谢!
试试这个:
>>> test[test!= True] = False
>>> test
0 True
1 False
2 False
3 False
4 False
5 True
dtype: object
这适用于花车。我可以重复整数。不过我相信还有更好的方法。
df.col_1.apply(lambda x: False if type(x)==float else x)
最简单的解决方案是比较 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
这里有一个玩具系列供说明之用。
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
谢谢!
试试这个:
>>> test[test!= True] = False
>>> test
0 True
1 False
2 False
3 False
4 False
5 True
dtype: object
这适用于花车。我可以重复整数。不过我相信还有更好的方法。
df.col_1.apply(lambda x: False if type(x)==float else x)
最简单的解决方案是比较 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