python - adding datime.datetime and datetime.time -
i trying add datetime.datetime , datetime.time 1 column. trying combine:
import datetime dt dt.datetime.combine(mydf['date'].astype(dt.date), mydf['time'].astype(dt.time))
but get:
typeerror: combine() argument 1 must datetime.date, not series
and trying this:
mydf['date'] + mydf['time']
but get
typeerror: unsupported operand type(s) +: 'datetime.datetime' , 'datetime.time'
does know, how can combine 2 colums?
date time 0 2011-08-08 00:00:00 08:10:00 1 2011-08-08 00:00:00 08:10:00 2 2011-08-08 00:00:00 08:10:00 3 2011-08-08 00:00:00 11:20:00 4 2011-08-08 00:00:00 12:25:00 5 2011-08-08 00:00:00 14:20:00
you trying combine whole columns, datetime.combine()
doesn't know how applied separate columns.
use dataframe.apply()
method instead:
def combine_cols(row): return dt.datetime.combine( row['date'].date(), row['time']) mydf.apply(combine_cols, axis=1)
axis=1
tells apply()
pass each row callable.
demo:
>>> import pandas pd >>> import datetime dt >>> mydf = pd.dataframe({ ... 'date': pd.series([dt.datetime(2011, 8, 8)] * 6), ... 'time': pd.series([dt.time(8, 10), dt.time(8, 10), dt.time(8, 10), dt.time(11, 20), dt.time(12, 25), dt.time(14, 20)]) ... }) >>> mydf date time 0 2011-08-08 08:10:00 1 2011-08-08 08:10:00 2 2011-08-08 08:10:00 3 2011-08-08 11:20:00 4 2011-08-08 12:25:00 5 2011-08-08 14:20:00 >>> def combine_cols(row): ... return dt.datetime.combine( ... row['date'].date(), row['time']) ... >>> mydf.apply(combine_cols, axis=1) 0 2011-08-08 08:10:00 1 2011-08-08 08:10:00 2 2011-08-08 08:10:00 3 2011-08-08 11:20:00 4 2011-08-08 12:25:00 5 2011-08-08 14:20:00 dtype: datetime64[ns]
wiki
Comments
Post a Comment