1

I have a column in data frame that contains years and it is stored as object datatype. It has values such as 1931to32,2009-10,1956-57,1951~52,1955-56,2017~18, I tried to change them in to a consistent format "yyyy" using pandas. df['TeamLaunch'] contains values such as 1931to32,2009-10,1956-57,1951~52,1955-56,2017~18, need to make make them uniform and consistent in the same format "1931,2009,1956,1951,1955,2017.

Tired this code, couldn't able to convert to "yyyy" format 
df['TeamLaunch'] = pd.to_datetime(df['TeamLaunch'], format="%Y"

1 Answer 1

0

If possible simplify problem by extract first 4 values of strings use:

df['TeamLaunch'] = df['TeamLaunch'].str[:4]

Or if need extract first year with 4 digits use:

df['TeamLaunch'] = df['TeamLaunch'].str.extract('(\d{4})')

Last convert to datetimes:

df['TeamLaunch'] = pd.to_datetime(df['TeamLaunch'], format="%Y")

If possible some values are not correct 4 digits use:

df['TeamLaunch'] = pd.to_datetime(df['TeamLaunch'], format="%Y", errors='coerce')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.