我正在尝试清理"凌乱"的日期并通过函数将它们转换为日-月-年格式。我已经测试了我的函数,它产生了正确的结果。
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 日
- 22-三月-76
- 1966/8/14
输出将是
- 1895.9.30
- 1976/3/22
- 1966/14/8
我正在尝试遍历子集中的列 ['dob'],它将替换旧值以new_Date_Str
subset:
dob
ID
1 30-Sep-1895
2 22-Mar-76
3 14/08/1966
我必须更改函数,使其不调用参数并遍历函数中 ['dob'] 中的每个值,但是,我对如何在不使用迭代行/元组的情况下遍历每一行有点困惑,因为它不鼓励。
.loc 是最好的方法吗?
更新:任何以两位数结尾的年份都应转换为 20 世纪年份。
熊猫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