Python Forum

Full Version: Applying Function With If
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I created a function with if statement to know which table to query and return a value to my dataframe, but I am getting truth value of series is ambiguous error.

Function if statement is as follows:
if s == "A":
   table = "mytable"
elseif s == "Z":
   table = "othertable"
I am creating new column and applying like:
df['newcol'] = df.apply(myfunc(df[col1],df[col2]), axis=1)
I have also tried axis = 0.

Any help is appreciated.
elseif?
And please show the full function definition (especially the return statement), and the full text of the error you are getting.
Here is a trimmed down version of my function (obviously cannot reference real table names here) Function:
 def myfunc(s, f): if s == "A": table = "mytable" elseif s == "Z": table = "othertable" sql = "SELECT COUNT(*) FROM " + table + " WHERE FIELD1 = " + str(f) result = [] result = pd.read_sql(sql, myconn) return result 
Here is how I am trying to use apply based on a search:
 df['newcol'] = df.apply(myfunc(df['s'],df['f']), axis=1) 
Here is the error
Error:
ValueError Traceback (most recent call last) <ipython-input-62-68c95646bc46> in <module>() ----> 1 df['newcol'] = df.apply(myfunc(df['s'],df['f']), axis=1) <ipython-input-60ecc5d8838b19> in myfunc(s, f) ---->4 if s == "A": raise ValueError("The truth value of a {0} is ambiguous. " "Use a.empty, a.bool(), a.item(), a.any() or a.all()." .format(self.__class__.__name__)) __bool__ = __nonzero__ ValueError" The truth value of a series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
First of all, you still have elseif in there. So that's not the code you're running because that would cause a syntax error.

Second, if you are returning the result of a sql call, that's going to be a sequence of rows matching the call. That's what the error is complaining about: "The truth value of a series is ambiguous." You need to convert the series to a boolean before your return it. Several ways of doing that are mentioned in the error text.
That elseif is what I had as it worked when I tested a single value. However, I've tried making it a if elif else and that doesn't and just if then, but I think it's still part of my error. In addition, where am I supposed to covert the series?

I tried this but it failed
return result.bool()
It's if/elif/else:

if condition:
    code
elif other_condition:
    more_code
else:
    yet_more_code
Try bool(result)
Is it because i have code after the if?

I presume all code must be inside the if statement?
In the code in your first post, you just need to replace elseif with elif. In your other code I can't tell, because it's all on one line. The indentation is important.