This is a question I come back to from time to time. I have a dataset where multiple columns (there are other columns, these are just the ones pertinent to the question) are used to indicate a date and time. After casting them from float to int I now have:
year mo dy hr min sec Valid Mag
1234 1886 9 1 2 51 4.0 7.3
1286 1893 6 4 2 27 4.0 7.0
1329 1897 8 5 0 10 4.0 7.7
1366 1901 8 9 9 23 4.0 7.2
1368 1901 8 9 18 33 4.0 7.4
What is the clearest and most idiomatic way to convert this as a DateTime in a DataFrame that has more than just columns related to date and time?
With a different project I used this:
sun['Date'] = sun['Year'].map(str)+ '-' + sun['Month'].map(str) + '-' + sun['Day'].map(str)
pd.to_datetime(sun['Date'], utc=False)
While this works, I think there certainly has to be a better, more generalized way. Specifically, I'm looking to combine the relevant fields into a DateTime but, again, there are other fields in the data frame. I've seen good responses for this in SQL, but that's not what I'm looking for.
Edit: I've received some solid answers for DataFrames of just date and times. However, the problem is that all result in the same error "ValueError: Length mismatch: Expected axis has 19 elements, new values have 6 elements" so I've added in a couple of extra columns.