A Byte of my 2.2-lb Brain

Just sharing stuff…

Add Multiple Columns to Pandas Dataframe from Function

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,
mydf[['hour', 'weekday', 'weeknum']] = mydf.apply(lambdafunc, axis=1)

More details can be found here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


This entry was posted on May 5, 2015 by in Geek and tagged , , .
%d bloggers like this: