Write a program in Python to filter valid dates in a given series

PythonPandasServer Side ProgrammingProgramming

Input − Assume, we have a Series,

0 2010-03-12 1 2011-3-1 2 2020-10-10 3 11-2-2

Output − And, the result for valid dates in a series is,

0 2010-03-12 2 2020-10-10

Solution 1

  • Define a Series.

  • Apply lambda filter method to validate a pattern in a series,

data = pd.Series(l)
result = pd.Series(filter(lambda x:re.match(r"\d{4}\W\d{2}\W\d{2}",x),data))
  • Finally, check the result to the series using the isin() function.

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
import re
l = ['2010-03-12','2011-3-1','2020-10-10','11-2-2']
data = pd.Series(l)
for i,j in data.items():
   if(re.match(r"\d{4}\W\d{2}\W\d{2}",j)):
      print(i,j)

Output

0    2010-03-12
2    2020-10-10
dtype: object

Solution 2

Example

import pandas as pd
import re
l = ['2010-03-12','2011-3-1','2020-10-10','11-2-2']
data = pd.Series(l)
result = pd.Series(filter(lambda x:re.match(r"\d{4}\W\d{2}\W\d{2}",x),data))
print(data[data.isin(result)])

Output

0    2010-03-12
2    2020-10-10
dtype: object
raja
Published on 10-Feb-2021 12:56:23
Advertisements