一系列按元素的布尔检查是含糊不清的

2024-04-20 13:03:26 发布

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

不知道如何使用.bool()、any、all或empty使这两个不同的示例正常工作。每一个都会抛出一个模糊的值错误

import pandas as pd


first = pd.Series([1,0,0])
second = pd.Series([1,2,1])

number_df = pd.DataFrame( {'first': first,  'second': second} )

bool_df = pd.DataFrame( {'testA': pd.Series([True, False, True]), 'testB': pd.Series([True, False, False])})

#ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

""" both the next two lines fail with the ambiguous Series issue"""
#each row should be true or false 
bool_df['double_zero_check'] = (number_df['first'] != 0) and (number_df['second'] != 0 )
bool_df['parity'] = bool_df['testA'] and bool_df['testB']

Tags: falsetruenumberdataframedfanyallempty
2条回答

您需要使用位and(&)来比较docs中的系列elementwise-more

In [3]: bool_df['double_zero_check'] = (number_df['first'] != 0) & (number_df['second'] != 0 )

In [4]: bool_df['parity'] = bool_df['testA'] & bool_df['testB']

In [5]: bool_df
Out[5]: 
   testA  testB double_zero_check parity
0   True   True              True   True
1  False  False             False  False
2   True  False             False  False

必须使用按位and(&;)运算符。and适用于布尔型,而不是熊猫系列。你知道吗

bool_df['double_zero_check'] = (number_df['first'] != 0) & (number_df['second'] != 0 )
bool_df['parity'] = bool_df['testA'] & bool_df['testB']

相关问题 更多 >