If you have a pandas data frame mydf
that has, for example, two columns mydate
and mytime
(both are of type datetime), to add three more columns: hour
, weekday
, and weeknum
, one can write and execute the following code chunk.
def getH(t): #gives the hour return t.hour def getW(d): #gives the week number return d.isocalendar()[1] def getD(d): #gives the weekday return d.weekday() # 0 for Monday, 6 for Sunday mydf["hour"] = mydf.apply(lambda row:getH(row["mytime"]), axis=1) mydf["weekday"] = mydf.apply(lambda row:getD(row["mydate"]), axis=1) mydf["weeknum"] = mydf.apply(lambda row:getW(row["mydate"]), axis=1)
Another approach (solution) is:
lambdafunc = lambda x: pd.Series([x['mytime'].hour, x['mydate'].isocalendar()[1], x['mydate'].weekday()]) mydf[['hour', 'weekday', 'weeknum']] = mydf.apply(lambdafunc, axis=1)
More details can be found here.