- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a program in Python to filter valid dates in a given series
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
Advertisements