Search code examples
pythoniterable-unpacking

Problems with tuple unpacking


In a function, i'm returning a list of two values if the values are there or an empty list, like below:

def func1(prikey):
    try:
      df = somesql
      for index, rW in df.iterrows():
          retvalue = [rW['id_in_int'],rW['time_in_str']]
    except:
        retvalue = []
    return retvalue

In the main code, i'm assigning to the variable:

newdf['newid'],newdf['thistime'] = func1(newdf['prikey'])

But i got the error "not enough values to unpack (expected 2, got 0)" So, in the function, i tried as below

retvalue = [[],[]]

But got the error as "Length of values does not match length of index" And retvalue = [0,0] didnt give any error and the value of newdf['newid'],newdf['thistime'] is zero.

And, when i'm trying to check whether the value is zero in further lines as if(newdf['newid']==0):, which gives the error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I tried checking len() as well which didnt work too. Any help is appreciated.


Solution

  • Thanks Shailesh and samy for your responses. Inside the function, i used retvalue = [0,0] to resolve "not enough values to unpack (expected 2, got 0)" error.

    The article https://towardsdatascience.com/apply-and-lambda-usage-in-pandas-b13a1ea037f7 helped me to use ".apply" on the series and below is the code.

    newdf['newwaittime'] = newdf['newid'].apply(lambda x: 0 if x==0 else get_new_wait_time(x))
    

    where I'm checking whether the value of newdf['newid'] is zero or not.