用 Python 编写一个程序来过滤给定系列中的有效日期
pythonpandasserver side programmingprogramming更新于 2024/6/17 2:20:17
输入 − 假设我们有一个系列,
0 2010-03-12 1 2011-3-1 2 2020-10-10 3 11-2-2
输出 −并且,系列中有效日期的结果是,
0 2010-03-12 2 2020-10-10
解决方案 1
定义一个系列。
应用 lambda 过滤器方法来验证系列中的模式,
data = pd.Series(l)
result = pd.Series(filter(lambda x:re.match(r"\d{4}\W\d{2}\W\d{2}",x),data))
最后,使用 isin() 检查系列结果函数。
示例
让我们看看以下实现以获得更好的理解。
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)
输出
0 2010-03-12 2 2020-10-10 dtype: object
解决方案 2
示例
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)])
输出
0 2010-03-12 2 2020-10-10 dtype:object
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

