Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Breaking a python string in pandas dataframe

I have a column ‘released’ which has values like ‘June 13, 1980 (United States)’

I want to get the year from this string so I tried using the following code

df['year_correct'] = df['released'].astype(str).str[',':'(']

But it is returning all the values as Nan in the new ‘year_correct’ column. Please help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A better way might be to extract the 4 digits value using words delimiter (\b) to ensure no more than 4 digits:

df['year_correct'] = df['released'].astype(str).str.extract(r'\b(\d{4})\b')

Example:

                        released year_correct
0  June 13, 1980 (United States)         1980
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading