0

The following line causes a ValueError (Pandas 17.1), and I'm trying to understand why.

x = (matchdf['ANPR Matched_x'] == 1)

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

I'm trying to use it for following conditional assignment:

matchdf.loc[x, 'FullMatch'] = 1

But I can't get past the previous issue.

I'm sure I've done this kind of thing dozens of times before, and I can't see why it should matter what is in the dataframe, but perhaps it does? or more likely, I'm probably making a silly mistake I just can't see!

Thanks for any help.

EDIT: For more context here's some preceding code:

inpairs = []
for m in inmatchedpairs:
    # more code
    p = {'Type In': mtype ,'Best In Time': besttime, 'Best G In Time': bestgtime,
         'Reg In': reg, 'ANPR Matched': anprmatch, 'ANPR Match Key': anprmatchkey}
    inpairs.append(p)

outpairs = []
for m in outmatchedpairs:
    # more code
    p = {'Type Out': mtype ,'Best Out Time': besttime, 'Best G Out Time': bestgtime,
         'Reg Out': reg, 'ANPR Matched': anprmatch, 'ANPR Match Key': anprmatchkey}
    outpairs.append(p)

indf = pd.DataFrame(inpairs)
outdf = pd.DataFrame(outpairs)
matchdf = pd.merge(indf, outdf, how='outer', on='ANPR Match Key')
matchdf['FullMatch'] = 0

x = (matchdf['ANPR Matched_x'] == 0)

I get the error on the last line.

2
  • 1
    This should work, can you provide an example? Commented Sep 1, 2016 at 16:43
  • I've added more of the example, but can't seem to replicate it elsewhere. Confused! Commented Sep 1, 2016 at 16:55

2 Answers 2

2

Use loc to set the values.

matchdf.loc[matchdf['APNR Matched_x'] == 1, 'FullMatch'] = 1

Example

df = pd.DataFrame({'APNR Matched_x': [0, 1, 1, 0], 'Full Match': [False] * 4})

>>> df
   APNR Matched_x Full Match
0               0      False
1               1      False
2               1      False
3               0      False

df.loc[df['APNR Matched_x'] == 1, 'FullMatch'] = 1

>>> df
   APNR Matched_x Full Match  FullMatch
0               0      False        NaN
1               1      False          1
2               1      False          1
3               0      False        NaN
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I think my problem must relate to what's in my DataFrame after the merge, or a Pandas bug of some kind then.
1

If you have this kind of error, first check your dataframe contains what you think it does.

I was stupidly ending up with some Series objects being added to one of the columns which should have contained ints!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.