'Printing date from Year, Month and Day columns in Pandas
I am looking to add a new column - "date" to my Pandas dataframe. Below are the first 5 rows of my dataframe: First 5 rows of the dataframe As seen from the image, the first column is year, second month, and third day. Below is what I have tried to do:
df['Year'] = pd.to_datetime(df[['Year','Month','Day']])
But, I keep getting the error as below:
ValueError: cannot assemble the datetimes: time data '610101' does not match format
'%Y%m%d' (match)
It would be great if I can get any help for the same.
Solution 1:[1]
try this:
df.apply(lambda x:'%s %s %s' % (x['year'],x['month'], x['day']),axis=1)
Solution 2:[2]
What about printing out what is actually showing for your selection first ?
print(df[['Year','Month','Day']])
if the data is indeed "610101", then you would likely need to modify it with '19':
pd.to_datetime('19' + df[['Year','Month','Day']])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abdullah Megahed |
| Solution 2 |
