我有一个DataFrame,我需要创建一个列,该列将具有Date格式的Date。其他数据框列包含月份,月份和月份。下面是示例。
答案 0 :(得分:0)
如果您想保留每月的确切日期,我相信这就是您要寻找的东西:
import pandas as pd
from datetime import datetime
df['Date'] = df['Birth Year'].astype(str) + "-" + df['Birth Month'].astype(str) + "-" + df['Day'].astype(str)
如果您想获得实际日期,则必须添加实际日期并像这样运行它:
df['Date'] = df.apply(lambda row: datetime(row['Birth Year'], row['Birth Month'], row['Day']), axis=1)
答案 1 :(得分:0)
尝试一下:
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"])
print(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
print(df.dtypes)
Birth Month int64
Birth Year int64
Day object
Date datetime64[ns] #Desired datetime format of pandas dataframe