tgunn
tgunn

Reputation: 935

Adding new values to Pandas DataFrame

I have a DataFrame where I need to add a new piece of information to each row - this piece of information is deduced from data already in the Data Frame.

Specifically I have a date, I want to take the date and run off to a service and return the Day of the Week, and insert it into that row in a new column:

Current Structure:

|Date      | Action1 | Action 2 |
=================================
|2014-10-15| a       | b        |
=================================
|2014-11-05| c       | d        |
=================================

The Goal is to get to this state:

|Date      |DOW    | Action1 | Action 2 |
========================================
|2014-10-15|Monday |a        | b        |
========================================
|2014-11-05|Tuesday|c        | d        |
========================================

I have a function that can intake a date and return the DOW,

def DOW(date):
   .....does some stuff....
   return Day_of_week

but I don't know how to best iterate over the dates in the DataFrame and insert the function return.

In a standard Dictionary i would just do:

for each in df:
   each.update({'DOW':DOW(each['Date']))

Upvotes: 0

Views: 121

Answers (1)

chrisaycock
chrisaycock

Reputation: 37930

You shouldn't have to iterate at all. Just do

df['DOW'] = df['Date'].map(DOW)

This will invoke your DOW() function on each element of Date in your Dataframe, and then assign the results to a column called DOW.

Upvotes: 2

Related Questions