F. Valle
F. Valle

Reputation: 117

Pandas function error: The truth value of a Series is ambiguous

I have a function to compared to date in a dataframe and return a value after a basic calculation:

def SDate(x,y):
    s=1
    a = min(x,y)
    b = max(x,y)
    if a !=x: s = -1
    r = b-a
    if b-a > 182:
        r = 365-b+a 
    return(r * s) 

I have tried using the following but I have an error:

df['Result']= SDate(df['GL Date'].dt.dayofyear,df['Special Date'].dt.dayofyear )

but I have an

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

Upvotes: 1

Views: 911

Answers (4)

Johny Mudly
Johny Mudly

Reputation: 324

I am not sure exactly what you are trying to achieve, but it looks like you are trying to set the inputs of a function to a series and get row wise outputs, which is unwise given that you want the output to be in the dataframe.

Its also good practice to include a sample of the data you are trying to use and what you want the output to look like, as well as a more detailed explanation of what you want to achieve.

That being said, from what you have described -you should use the apply method as a row wise operation to get your output.

So if you wish to apply this function:

def SDate(x,y):
    s=1
    a = min(x,y)
    b = max(x,y)
    if a !=x: s = -1
    r = b-a
    if b-a > 182:
        r = 365-b+a 
    return(r * s) 

You should do this:

df['Result'] = df.apply(lambda x: SDate(x['GL Date'].dt.dayofyear, x['Special Date'].dt.dayofyear), axis = 1)

Upvotes: 1

Mohit Motwani
Mohit Motwani

Reputation: 4792

You can try axis parameter of df.apply:

def SDate(row):
    s=1
    year1=row['GL Date'].year
    year2= row['Special Date'].year
    a = min(year1,year2)
    b = max(year1,year2)
    if a !=year1:
        s = -1
    r = b-a
    if b-a > 182:
        r = 365-b+a 
    return(r * s) 

df['Result']= df.apply(SDate, axis=1)

When you Pass the GL Date and Special Date years to the functions, you're actually passing in a Series The error is because you can't compare values of Series with < or > operators. So the results is ambiguous. Which is greater can't be determined. Hence the error that you got.

When you use apply functions axis=1, it applies the function row-wise.

Upvotes: 0

AivanF.
AivanF.

Reputation: 1216

The problem is about min/max functions, they don't work with Series objects. Consider using this:

a = min(x.min(), y.min())
b = max(x.max(), y.max())

However, then you compare Series with a number: if a != x: – it will fail too. What's the purpose of your function?

Upvotes: 0

Angelo
Angelo

Reputation: 655

You are giving as x and as y a Pandas Series. Therefore, the function min cannot recieve such object. As I don't know what are you doing there I can't fix that on code.

Hope it works.

Upvotes: 0

Related Questions