首页 > 解决方案 > 如何从给定的输入中检索日期

问题描述

我有一个 DataFrame,我需要创建一个包含日期格式的日期的列。其他数据框列包含月份、年份和月份中的日期。下面是示例。

在此处输入图像描述

标签: python

解决方案


尝试这个:

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

推荐阅读