We help IT Professionals succeed at work.
Private
Troubleshooting Question

# Error

on
32 Views
`df['new_year'] = [df['Year'] if x.isin([1,2,3,4,5,6,7,8]) else df['Year']+1 for x in df['Month']]`

`AttributeError: 'int' object has no attribute 'isin'`
Logic I am trying to apply: create a new column in which if value in the column month is from 1 to 8, then value in the column year will be same i.e df['Year'] else there will be an addition of 1 to the year i.e. df['Year]+1.

Comment
Watch Question

## View Solutions Only

CERTIFIED EXPERT

Commented:
I guess you should use instead
if df['Month'].isin([1,2,3,4,5,6,7,8])

Commented:
I used df['Month]. Got valueError.

``````df['new_year'] = [df['Year'] if df['Month'].isin([1,2,3,4,5,6,7,8]) else df['Year']+1 for x in df['Month']]
``````

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

Commented:
pandas...
so should be
(df['Month']  >= 1) &( df['Month'] <= 8)

Commented:
``````df1['new_year'] = [df1['Year'] if ((x>=1)&(x<=8)) else df1['Year']+1 for x in df1['Month']]
``````

No error but wrong output.
Please see the snapshot below. It prints all the years for every row in month.

Please see the snapshot below. I wanted the output like below for the given input
CERTIFIED EXPERT

Commented:
Why do you use x?
and looping for every value in x it returns a  new_year value

df1['new_year']  = [df1['Year'] if ((df['Month']  >= 1) & ( df['Month'] <= 8)) else df1['Year']+1]

Commented:
I had tried with this one but I get value error.
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Commented:
``````df1['harvest_year'] = [df1['Year'] if ((df1['Month']>=1)&(df1['Month']<=8)) else df1['Year']+1 for x in df1['Month']]
``````

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

I think I am making error with some syntax or  pandas.

Commented:
``````temp = set(map(lambda i : i, df1['Month']))

df1['new_year'] = [df1['Year'] if ((df1['Month']>=1)&(df1['Month']<=8)) else df1['Year']+1 for x in temp]
``````

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

Commented:
try this way
`df1['new_year'] = df1['Month'].apply(lambda x: df1['Year']  if (x >= 1) & (x <= 8) else df1['Year']+1)`

Commented:
Worked. Thanks.  I just had to add 1 line before. create an empty column.

df1['new_year'] = ''
df1['new_year'] = df1['Month'].apply(lambda x: df1['Year'] if ((x >= 1) & (x <= 8)) else df1['Year']+1)
CERTIFIED EXPERT
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
CERTIFIED EXPERT
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)

Commented:
Yes, I needed the ID. Working fine.
Thanks.
CERTIFIED EXPERT

Commented:
You're welcome.