Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรม Python กรองวันที่ถูกต้องใน Series


อินพุต - สมมติเรามี Series

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

เอาต์พุต - ผลลัพธ์วันที่ถูกต้องใน Series

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

วิธีที่ 1

  • สร้าง Series

  • ใช้ filter กับ lambda และ regex รูปแบบ YYYY-MM-DD

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