[英]converting Month and Year to Datetime
我有一個數據集,其中月份和年份為單獨的列。 我想創建一個包含Date的Date的新列,在這種情況下,它可能是每月的1號。
Month Year
1 2013
1 2013
2 2013
2 2013
df['Date'] = pd.to_datetime(df['Month'])
預期產量:
Month Year Date
1 2013 1/1/2013
1 2013 1/1/2013
2 2013 1/2/2013
2 2013 1/2/2013
format = %d%m%y
您可以在to_datetime
指定格式,如下所示:
df['Date']=df.apply(lambda row: pd.to_datetime(str(row.Month) + '/'+ str(row.Year)), axis = 1)
df = pd.DataFrame({'Month':[1,1,2,2], 'Year':[2013, 2013, 2013, 2013]})
# apply each single row with this lambda function
df['Date'] = df.apply(lambda row: '1' + '/' + str(row.Month) + '/'+ str(row.Year), axis = 1)
print(df.to_string(index=False))
輸出是
Month Year Date
1 2013 1/1/2013
1 2013 1/1/2013
2 2013 1/2/2013
2 2013 1/2/2013
我嘗試了一些方法,發現幾乎所有結果都與您的要求相同,它們通常像這樣01/02/2012
。 如果您不喜歡“ 0”,可以嘗試這種方式,但是有點復雜
temp = pd.DataFrame({"Year":df["Year"],"Month":df['Month'],"day":1})
a = pd.to_datetime(temp)
c = []
for item in a:
c.append(str(item.day) + "/" + str(item.month) + "/" + str(item.year))
df['Date'] = c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.