首页 > 解决方案 > 对列中的每一行应用数据清洗日期函数

问题描述

我正在尝试清理“凌乱”的日期并通过函数将它们转换为日月年格式。我已经测试了我的功能,它产生了正确的结果。

def date_change(strDate):
    if ("-") in strDate:
        sp_Str_Dob= strDate.split("-")
    elif ("/") in strDate:
        sp_Str_Dob= strDate.split("/")

    if len(strDate)==4:
        return (strDate)
#day processing
    length_Day= len(sp_Str_Dob[0])
    if length_Day ==1:
        new_Day= str(("0" + sp_Str_Dob[0]))
    else:
        new_Day= str(sp_Str_Dob[0])
#month processing
    strMonth= (sp_Str_Dob[1])
    if (len(strMonth)) ==3:
        new_Month= str((strptime(strMonth,'%b').tm_mon)) #change letter month to number
    else:
        new_Month= str((strptime(strMonth,'%m').tm_mon)) #month is number
#year processing
    strYear= (sp_Str_Dob[2])
    length_Year= len(sp_Str_Dob[2])
    if length_Year ==2: #if only two digits then 20th cemtury
       new_Year= str("19" + sp_Str_Dob[2])
    else:
        new_Year= str(sp_Str_Dob[2]) 

    new_Date_Str= (new_Day + "/" + new_Month + "/" + new_Year)
    print(new_Date_Str)

目前,如果输入是:

输出将是

我正在尝试遍历子集中的列 ['dob'],它将旧值替换为 new_Date_Str

subset:

    dob
ID
1   30-Sep-1895
2   22-Mar-76
3   14/08/1966

我将不得不更改函数,因此它不调用任何参数并在我的函数中遍历 ['dob'] 中的每个值,但是,我对如何在不使用 iterrows/tuples 的情况下遍历每一行感到有些困惑气馁。

.loc 是最好的方法吗?

更新:任何以两位数结尾的年份都应转换为 20 世纪年份。

标签: pythonpandasbigdata

解决方案


Pandasto_datetime可以处理不同格式的日期时间,它将以月份优先格式返回日期。您可以使用strftime将这些转换为 day-first 但日期将是对象类型,而不是datetime.

df['dob'] = pd.to_datetime(df['dob']).dt.strftime('%d/%m/%Y')

    dob
ID  
1   30/09/1895
2   22/03/1976
3   14/08/1966

推荐阅读