'How can I create a new column which consists on the sum of two columns in a pandas data frame?
I am trying to put together 2 columns of a data frame, one is 'Date' and the other is 'Time', so I want to create a column called 'Date and Time'. My dataframe is called GLE_48. So I tried this:
GLE_48['Date and Time'] = GLE_48['Date']+GLE_48['Time']
To this, I get the following Error:
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'datetime.time'
I tried to solve it by applying the next tool:
GLE_48['Date and Time'] = GLE_48['Date']+GLE_48['Time'].map(pd.Timedelta.to_pytimedelta)
and I got:
'TypeError: descriptor 'to_pytimedelta' for 'pandas._libs.tslibs.timedeltas._Timedelta' objects doesn't apply to a 'datetime.time' object
So, I have been unable to do anything else, I am not very used to pandas yet, does anyone have a suggestion?
Solution 1:[1]
I figured it out by using the next code:
GLE_48["Date and Time"] = pd.to_datetime(GLE_48['Date'].astype(str) + GLE_48['Time'].astype(str), format="%Y-%m-%d%H:%M:%S")
I found it easier to turn the columns into 'string' type and then putting the columns together than turning the columns into the same 'datetime' format.
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 | Ynjxsjmh |
