Home > Enterprise >  The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). How t
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). How t

Time:10-24

I have a dataframe like

found_record
    Unnamed: 0                          AID         AnotherID                      otherID PositionType    CreatedVer     LatestVer DeleteFlag
194        162  00000000000000010601233000119682  129030_503520  00000000000020010601233000119678            2  000190010111  000190010111          0

and I do

found_record['PositionType']
194    2
Name: PositionType, dtype: object

This is a Series

I want to compare the position type of this record to a number (for example 2)

but when I do

if found_record['PositionType']==2:
(Pdb) n
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can I compare it?

p.s. I tried

condition(found_record['PositionType']==2)
*** Non-numeric breakpoint number (found_record['PositionType']==2)

CodePudding user response:

You still have 2 steps to extract the value and compare it to a number:

  1. extract the value of the pandas cell. As a dataframe is a 2D animal (2 axes: index and columns), you need a double dereferencement. If you are sure of the index value, you can do simply

     found_record[194, 'PositionType']  # should be 2, or maybe the string '2'
    

    if unsure, you can just extract the first value of the Series:

     found_record['PositionType'].iloc[0]  # id. 2 or '2'
    
  2. convert the retrieved object to a number (here an integer) because you already know that the Series has not an integer dtype (you showed it is object)

     int(found_record['PositionType'].iloc[0])   # will be 2
    
  • Related