Extract date from a specified column of a given Pandas DataFrame using Regex

In this article, we will discuss how to extract only valid date from a specified column of a given Data Frame. The extracted date from the specified column should be in the form of  ‘mm-dd-yyyy’.

Approach:

In this article, we have used a regular expression to extract valid date from the specified column of the data frame. Here we used \b(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/([0-9]{4})\b this regular expression. We’ll be using re.findall() method for this. Now let us try to implement this using Python: 

Step 1: Creating Dataframe



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas and re library
import pandas as pd
import re as re
  
# creating data frame with column
# name,date_of_birth and age
df = pd.DataFrame({'Name': ['Akash', 'Shyam', 'Ayush',
                            'Diksha', 'Radhika'],
  
                   'date_of_birth': ['12/21/1998', '15/12/1998',
                                     '06/11/2000', '05/10/1998',
                                     '13/12/2010'],
  
                   'Age': [21, 12, 20, 21, 10]})
  
# printing the original data frame
print("Printing the original dataframe")
df

chevron_right


Output:

Step 2: Extracting valid date from data frame in the format ‘mm-dd-yyyy’

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# creating function to find whether the 
# given date is valid or not
def checking_valid_dates(dt):
      
    # creating regular expression to check 
    # whether date fall in the format 
    # mm-dd-yyyy
    result = re.findall(
        r'\b(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/([0-9]{4})\b', dt)
    return result
  
  
# creating new column with valid_date_of_birth
df['valid_date_of_birth'] = df['date_of_birth'].apply(
    lambda dt: checking_valid_dates(dt))
  
print("\nPrinting the data frame Valid dates in the format: mm-dd-yyyy:")
df

chevron_right


Output:


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.