Date formating in Pandas

Viewed 38

I'm trying to format a column with date to 'Month Year' format without changing non-date values .

input_df = pd.DataFrame({'Period' :['2017-11-01 00:00:00', '2019-02-01 00:00:00', 'Mar 2020', 'Pre-Nov 2017', '2019-10-01 00:00:00' , 'Nov 17-Nov 18'] } )

input_df is

enter image description here

expected output is:

enter image description here

I tired with the below code which didn't work:

output_df['Period'] = input_df['Period'].apply(lambda x: x.strftime('%m %Y') if isinstance(x, datetime.date) else x)

Pls help..

1 Answers

You can do with error='coerce' and fillna:

input_df['new_period'] = (pd.to_datetime(input_df['Period'], errors='coerce')
       .dt.strftime('%b %Y')
       .fillna(input_df['Period'])
    )

Output:

                Period     new_period
0  2017-11-01 00:00:00       Nov 2017
1  2019-02-01 00:00:00       Feb 2019
2             Mar 2020       Mar 2020
3         Pre-Nov 2017   Pre-Nov 2017
4  2019-10-01 00:00:00       Oct 2019
5        Nov 17-Nov 18  Nov 17-Nov 18

Update: Second, safer option:

s = pd.to_datetime(input_df['Period'], errors='coerce')

input_df['new_period'] = np.where(s.isna(), input_df['Period'], 
                                  s.dt.strftime('%b %Y'))
Related