0

Suppose I have a string "03/25/93" which is in a pandas series. I want to find /93 first and then replace it with /1993. How do I go about it?

The pandas series is 03/25/93
6/18/85
7/8/71
9/27/75
2/6/96

I want this to be 03/25/1993
6/18/1985
7/8/1971
9/27/1975
2/6/1996

df.str.replace(r'[/]\d{2}$', '/19??')

2 Answers 2

2

Use \1 to reference a match

>>> df.str.replace(r'/(\d{2})$', r'/19\1')
0    03/25/1993
1     6/18/1985
2      7/8/1971
3     9/27/1975
4      2/6/1996
dtype: object
Sign up to request clarification or add additional context in comments.

Comments

2

Using to_datetime with strftime

pd.to_datetime(s,format='%m/%d/%y').dt.strftime('%m/%d/%Y')
Out[937]: 
0    03/25/1993
1    06/18/1985
2    07/08/1971
3    09/27/1975
4    02/06/1996
Name: S, dtype: object

1 Comment

thanks it cleared my doubt, but I have a question what if the series also contains some data which has year as YYYY, then it would throw me an error

Your Answer

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