2

I have written a code to do a date modification to reduce 1 day on 2/29/2008. The code successfully executes and shows me the output but it does not update the dataframe.

Name    Maint Start Date
Yasin   02/29/08
Susy    01/04/15
James   04/14/06

I wrote the below code it gave me the output but it did not update the dataframe

spend_sw[spend_sw['Maint Start Date'] == '02/29/2008'].apply(lambda x: pd.datetime(x['Maint Start Date'].year , x['Maint Start Date'].month, x['Maint Start Date'].day - 1), axis=1) 

Then I modified it to but all the fields which did not have the leap year dat became blank.

spend_sw['Maint Start Date'] = spend_sw[spend_sw['Maint Start Date'] == '02/29/2008'].apply(lambda x: pd.datetime(x['Maint Start Date'].year , x['Maint Start Date'].month, x['Maint Start Date'].day - 1), axis=1) 

Can you please tell me how can I modify the values to the existing dataframe.

1 Answer 1

2

I think you can first convert all values in column Maint Start Date to_datetime, then filter with ix and subtract Timedelta one day created by to_timedelta:

print (spend_sw)
    Name Maint Start Date
0  Yasin         02/29/08
1   Susy         01/04/15
2  James         04/14/06

spend_sw['Maint Start Date'] = pd.to_datetime(spend_sw['Maint Start Date'])

print (spend_sw.ix[spend_sw['Maint Start Date'] == '02/29/08', 'Maint Start Date'])
0   2008-02-29
Name: Maint Start Date, dtype: datetime64[ns]

spend_sw.ix[spend_sw['Maint Start Date'] == '02/29/08', 'Maint Start Date'] = \
spend_sw.ix[spend_sw['Maint Start Date'] == '02/29/08', 'Maint Start Date'] - 
pd.to_timedelta(1, unit='d') 
print (spend_sw)
    Name Maint Start Date
0  Yasin       2008-02-28
1   Susy       2015-01-04
2  James       2006-04-14

Another solution with mask and offset:

spend_sw['Maint Start Date'] = pd.to_datetime(spend_sw['Maint Start Date'])

date = pd.to_datetime('02/29/08')
date1 = date - pd.offsets.Day(1)
#mask by condition
ma = spend_sw['Maint Start Date'] == date
spend_sw['Maint Start Date'] = spend_sw['Maint Start Date'].mask(ma, date1)
print (spend_sw)
    Name Maint Start Date
0  Yasin       2008-02-28
1   Susy       2015-01-04
2  James       2006-04-14
Sign up to request clarification or add additional context in comments.

1 Comment

Hi...I tried the solution and it worked perfectly fine. Also I had to do some more date manipulations of adding years referring to an Name and it worked exactly how I needed it.

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.