【发布时间】: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 世纪年份。
【问题讨论】: