I have a dataset with Month and Year as separate columns. I want to create a new column with Date with includes the Day , in this case it could be the 1st of every month.
Month Year
1 2013
1 2013
2 2013
2 2013
df['Date'] = pd.to_datetime(df['Month'])
Expected output :
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))
Output is
Month Year Date
1 2013 1/1/2013
1 2013 1/1/2013
2 2013 1/2/2013
2 2013 1/2/2013
I have tried some ways and I found that nearly all results have same point that dif f with your demands, they are usually like this 01/02/2012
. if you don't like "0", you can try this way but a little complex
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.