1

I have a dataframe

 id |start|stop|join_date
 233| 0   | 12 |2015-01-01
 234| 0   | 12 |2013-03-04
 235| 10  | 23 |2014-01-10

GOAL:

I want to create another column stop_date that offsets the join_date based on whether or not the start date is 0.

If the start is 0 then stop_date is the join_date is offset by the months in stop

If the start is not 0 then stop_date is the join_date is offset by the months in stop and the months in start

I wrote the following function:

def stop_date(x):
    if x['start'] == 0:
        return x['join_date'] + x['stop'].astype('timedelta64[M]')
    elif x['start'] != 0 :
        return x['join_date'] + x['start'].astype('timedelta64[M]') + x['stop'].astype('timedelta64[M]')
    else:
        return x

I tried to apply to the dataframe by:

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

I keep getting an error : AttributeError: ("'int' object has no attribute 'astype'", 'occurred at index 0') I cannot figure out how to achieve this.

1
  • Please provide the entire error message, as well as a minimal reproducible example. It seems rather clear to me, what specifically do/don't you understand from that error message? Commented Apr 27, 2020 at 2:44

2 Answers 2

2

Because when start is 0, doing the sum of start and stop won't change the number of month to add, you can sum both, convert with astype and add the 'join_date':

df['stop_date'] = (pd.to_datetime(df['join_date']) 
                   + df[['start', 'stop']].sum(axis=1).astype('timedelta64[M]')
                  ).dt.date

print (df)
    id  start  stop   join_date   stop_date
0  233      0    12  2015-01-01  2016-01-01
1  234      0    12  2013-03-04  2014-03-04
2  235     10    23  2014-01-10  2016-10-10
Sign up to request clarification or add additional context in comments.

Comments

0

Convert the columns to the desired dtype before you apply the function. x['stop'] is a scalar value of the datatype of the column (e.g., 12), so it has no dataframe or series methods, such as astype.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.