0

I have a dataframe called fresp, and in command line I can do this:

for i in range(0,len(fresp)):
    num=fresp.at[i,'caseid']

And that works just fine. The exact same code, when saved in a .py file, gives me:

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

specifically in reference to num=fresp.at[i,'caseid'].

Here is the whole function. When I save it in a .py file, import the function, and run it, I get the error. When I just copy the whole thing into command line (minus then first def line), it runs just fine. Why would this be?

def ValidatePregs(df,fresp):
    pregmap=MakePregMap(df)
    counter=0
    for i in range(0,len(fresp)):
        case=fresp.at[i,'caseid']
        num=fresp.at[i,'pregnum']
        if num == 0 and case in pregmap:
            print("Mismatch for "+case+".")
            counter +=1
        elif num != len(pregmap[case]):
            print("Mismatch for "+case+".")
            counter +=1
    if counter==0:
        print("No mismatches!")

(I'm reading/doing Think Stats 2.0.35 by Allen B. Downey. I'm working on Exercise 1. I know there's a more elegant solution, but I still want to know why this does/doesn't work.)

1
  • How are you calling the function ValidatePregs, and what are the first few lines of your data? Commented Apr 4, 2018 at 21:17

1 Answer 1

1

I think I know your problem: In these lines:

num=fresp.at[i,'pregnum']
if num == 0 and case in pregmap:

You try to fetch a row using at which is similar to loc and returns a pd.Series object. When you do the comparison, Python is comparing the pd.Series which has an ambiguous truth value.

To avoid this, you can use iloc to fetch the row, and then access the pregnum value:

num = fresp.iloc[i].pregnum
if num ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.