簡體   English   中英

如何從給定的輸入中檢索日期

[英]How to retrieve date from a given input

我有一個 DataFrame 並且我需要創建一個將日期格式為日期的列。 其他 dataframe 列包含月、年和月日。 下面是示例。

在此處輸入圖像描述

如果您想保留每月的字面日期,我相信這就是您要尋找的:

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)

在此處輸入圖像描述

嘗試這個:

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"])

Output:

打印(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM