python - 对列中的每一行应用数据清洗日期函数
问题描述
我正在尝试清理“凌乱”的日期并通过函数将它们转换为日月年格式。我已经测试了我的功能,它产生了正确的结果。
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/tuples 的情况下遍历每一行感到有些困惑气馁。
.loc 是最好的方法吗?
更新:任何以两位数结尾的年份都应转换为 20 世纪年份。
解决方案
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
推荐阅读
- javascript - 如何从 mongo 渲染项目?
- reactjs - 如何使用 UUID 从集合中删除项目?
- r - 是否可以使用单个“geom_boxplot()”来对不带分面的分组部分箱线图进行ggplot?
- excel - 如何找到字母数字字符串中的最后 2 个字母?
- python - if语句不满足时如何停止代码运行
- tensorflow - 理解 Tensorflow Keras 层的计算图
- go - 遍历对数组
- javascript - 用远程文件中的 JSON 替换教程代码中的数据
- javascript - 如何将 ruby 正则表达式转换为 javascript 正则表达式?
- authentication - 内置认证机制——API网关