简体   繁体   中英

pandas Series elementwise boolean checks are ambigious

Not sure how to use .bool(), any, all, or empty, to make the two different examples work. Each throws me the Ambiguous Value error

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']

You need to use the bitwise and ( & ) to compare Series elementwise - more in the docs

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

You have to use the bitwise and (&) operator. and works for boolean not for Pandas Series.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM