python - 如何从给定的输入中检索日期
问题描述
我有一个 DataFrame,我需要创建一个包含日期格式的日期的列。其他数据框列包含月份、年份和月份中的日期。下面是示例。
解决方案
尝试这个:
import pandas as pd
import datetime as datetime
df = #Your input dataframe
#Extract the day, month and year into a single column
df["Date"] = df['Day'].astype(str).str[0] + df["Birth Month"].map(str) + df["Birth Year"].map(str)
#Convert it into a string format consisiting of the date
df["Date"] = df['Date'].apply(lambda x:datetime.strptime(x,'%d%m%y').date())
#Now convert the column into pandas datetime format
df["Date"] = pd.to_datetime(df["Date"])
输出:
打印(df)
Birth Month Birth Year Day Date
0 5 88 1st Monday 1988-05-01
1 10 87 3rd Tuesday 1987-10-03
2 12 87 2nd Saturday 1987-02-21
3 1 88 1st Tuesday 1988-01-01
4 2 88 1st Monday 1988-02-01
打印(df.dtypes)
Birth Month int64
Birth Year int64
Day object
Date datetime64[ns] #Desired datetime format of pandas dataframe
推荐阅读
- android - 对话框弹出很慢
- numpy-ndarray - 从python中的数据集中过滤索引
- html - Bootstrap模态滚动条在触发另一个模态后出现和消失
- authentication - istio 得到“RBAC:访问被拒绝”,即使服务角色绑定被检查为允许
- android - 测试用例在 Firebase 测试实验室失败,但在本地机器上工作
- docker - 如何从 dockerised ELK 中清除日志文件?
- jwt - 如何从 JWKSet 文件中签署 JWT?
- ios - 如何减少 Xcode 链接时间?
- python-3.x - 如何使用 sklearn 计算 Precision、Recall 和 F1 分数
- html - 如何使旋转的元素居中并将其与顶部对齐?