【问题标题】:Apply data cleaning date function to each row in column对列中的每一行应用数据清洗日期函数
【发布时间】:2019-03-29 02:42:31
【问题描述】:

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

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)

当前如果输入是:

  • 1895 年 9 月 30 日
  • 76 年 3 月 22 日
  • 1966 年 8 月 14 日

输出将是

  • 1895 年 9 月 30 日
  • 22/3/1976
  • 1966 年 14 月 8 日

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

subset:

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

我必须更改函数,使其不调用任何参数,并在我的函数中遍历 ['dob'] 中的每个值,但是,我对如何在不使用 iterrows/ 的情况下遍历每一行感到有些困惑不鼓励使用元组。

.loc 是最好的方法吗?

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

【问题讨论】:

    标签: python pandas bigdata


    【解决方案1】:

    Pandas to_datetime 可以处理不同格式的日期时间,它将以月份优先格式返回日期。您可以使用strftime 将这些转换为第一天,但​​日期将是对象类型,而不是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
    

    【讨论】:

    • 领先我一秒 +1
    • @U9-Forward,一直在发生 :)
    • 大声笑 :-) 人们以前也对我说过 :-)
    • 感谢@Vaishali 虽然该列现在包含正确的格式,但我收到了 SettingWithCopyWarning
    • 您是否通过复制列从另一个数据框创建了此数据框?这应该是获得 SettingWithCopyWarning 的唯一原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多