Say I have a dataframe with 3 columns: Date, Ticker, Value (no index, at least to start with). I have many dates and many tickers, but each (ticker, date)
tuple is unique. (But obviously the same date will show up in many rows since it will be there for multiple tickers, and the same ticker will show up in multiple rows since it will be there for many dates.)
Initially, my rows in a specific order, but not sorted by any of the columns.
I would like to compute first differences (daily changes) of each ticker (ordered by date) and put these in a new column in my dataframe. Given this context, I cannot simply do
df['diffs'] = df['value'].diff()
because adjacent rows do not come from the same ticker. Sorting like this:
df = df.sort(['ticker', 'date'])
df['diffs'] = df['value'].diff()
doesn't solve the problem because there will be "borders". I.e. after that sort, the last value for one ticker will be above the first value for the next ticker. And computing differences then would take a difference between two tickers. I don't want this. I want the earliest date for each ticker to wind up with an NaN
in its diff column.
This seems like an obvious time to use groupby
but for whatever reason, I can't seem to get it to work properly. To be clear, I would like to perform the following process:
- Group rows based on their
ticker
- Within each group, sort rows by their
date
- Within each sorted group, compute differences of the
value
column
- Put these differences into the original dataframe in a new
diffs
column (ideally leaving the original dataframe order in tact.)
I have to imagine this is a one-liner. But what am I missing?
Edit at 9:00pm 2013-12-17
Ok...some progress. I can do the following to get a new dataframe:
result = df.set_index(['ticker', 'date'])
.groupby(level='ticker')
.transform(lambda x: x.sort_index().diff())
.reset_index()
But if I understand the mechanics of groupby, my rows will now be sorted first by ticker
and then by date
. Is that correct? If so, would I need to do a merge to append the differences column (currently in result['current']
to the original dataframe df
?
See Question&Answers more detail:
os