Change type Column with 2 format Python

Annis15 :

Hello World,

New in Python, I am trying to convert a column (YEAR) into one format.

The column contains 2 formats: - yy - yyyy

Here is an example

year
2007
07
1999
2001
99

What I have tried is to fill 20 before year column but what about when date is 99.

The desire output will be something like

year   new_year
2007   2007
07     2007
1999   1999
2001   2001
99     1999

Thanks for anyone helping

jezrael :

Use to_datetime with format for YY - %y and errors='coerce' and with Series.dt.year, so non format YY return missing values replaced by original with Series.fillna:

df['new_year'] = (pd.to_datetime(df['year'], format='%y', errors='coerce').dt.year
                    .fillna(df['year'])
                    .astype(int))
print (df)
   year  new_year
0  2007      2007
1    07      2007
2  1999      1999
3  2001      2001
4    99      1999

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297593&siteId=1