|
| 1 | +''' |
| 2 | +Utility functions for multi-index dataframes. Useful for creating bi-temporal timeseries. |
| 3 | +''' |
| 4 | +from datetime import datetime |
| 5 | +import logging |
| 6 | +import types |
| 7 | + |
| 8 | +from pandas.tseries.tools import to_datetime as dt |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +import pandas as pd |
| 12 | + |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +# ----------------------- Grouping and Aggregating ---------------------------- # |
| 18 | + |
| 19 | +def fancy_group_by(df, grouping_level=0, aggregate_level=1, method='last', max_=None, min_=None, within=None): |
| 20 | + """ Dataframe group-by operation that supports aggregating by different methods on the index. |
| 21 | +
|
| 22 | + Parameters |
| 23 | + ---------- |
| 24 | + df: ``DataFrame`` |
| 25 | + Pandas dataframe with a MultiIndex |
| 26 | + grouping_level: ``int`` or ``str`` or ``list`` of ``str`` |
| 27 | + Index level to group by. Defaults to 0. |
| 28 | + aggregate_level: ``int`` or ``str`` |
| 29 | + Index level to aggregate by. Defaults to 1. |
| 30 | + method: ``str`` |
| 31 | + Aggregation method. One of |
| 32 | + last: Use the last (lexicographically) value from each group |
| 33 | + first: Use the first value from each group |
| 34 | + max_: <any> |
| 35 | + If set, will limit results to those having aggregate level values <= this value |
| 36 | + min_: <any> |
| 37 | + If set, will limit results to those having aggregate level values >= this value |
| 38 | + within: Any type supported by the index, or ``DateOffset``/timedelta-like for ``DatetimeIndex``. |
| 39 | + If set, will limit results to those having aggregate level values within this range of the group value. |
| 40 | + Note that this is currently unsupported for Multi-index of depth > 2 |
| 41 | + """ |
| 42 | + if method not in ('first', 'last'): |
| 43 | + raise ValueError('Invalid method') |
| 44 | + |
| 45 | + if isinstance(aggregate_level, basestring): |
| 46 | + aggregate_level = df.index.names.index(aggregate_level) |
| 47 | + |
| 48 | + # Trim any rows outside the aggregate value bounds |
| 49 | + if max_ is not None or min_ is not None or within is not None: |
| 50 | + agg_idx = df.index.get_level_values(aggregate_level) |
| 51 | + mask = np.full(len(agg_idx), True, dtype='b1') |
| 52 | + if max_ is not None: |
| 53 | + mask &= (agg_idx <= max_) |
| 54 | + if min_ is not None: |
| 55 | + mask &= (agg_idx >= min_) |
| 56 | + if within is not None: |
| 57 | + group_idx = df.index.get_level_values(grouping_level) |
| 58 | + if isinstance(agg_idx, pd.DatetimeIndex): |
| 59 | + mask &= (group_idx >= agg_idx.shift(-1, freq=within)) |
| 60 | + else: |
| 61 | + mask &= (group_idx >= (agg_idx - within)) |
| 62 | + df = df.loc[mask] |
| 63 | + |
| 64 | + # The sort order must be correct in order of grouping_level -> aggregate_level for the aggregation methods |
| 65 | + # to work properly. We can check the sortdepth to see if this is in fact the case and resort if necessary. |
| 66 | + # TODO: this might need tweaking if the levels are around the wrong way |
| 67 | + if df.index.lexsort_depth < (aggregate_level + 1): |
| 68 | + df = df.sortlevel(level=grouping_level) |
| 69 | + |
| 70 | + gb = df.groupby(level=grouping_level) |
| 71 | + if method == 'last': |
| 72 | + return gb.last() |
| 73 | + return gb.first() |
| 74 | + |
| 75 | + |
| 76 | +# --------- Common as-of-date use case -------------- # |
| 77 | + |
| 78 | +def groupby_asof(df, as_of=None, dt_col='sample_dt', asof_col='observed_dt'): |
| 79 | + ''' Common use case for selecting the latest rows from a bitemporal dataframe as-of a certain date. |
| 80 | +
|
| 81 | + Parameters |
| 82 | + ---------- |
| 83 | + df: ``pd.DataFrame`` |
| 84 | + Dataframe with a MultiIndex index |
| 85 | + as_of: ``datetime`` |
| 86 | + Return a timeseries with values observed <= this as-of date. By default, the latest observed |
| 87 | + values will be returned. |
| 88 | + dt_col: ``str`` or ``int`` |
| 89 | + Name or index of the column in the MultiIndex that is the sample date |
| 90 | + asof_col: ``str`` or ``int`` |
| 91 | + Name or index of the column in the MultiIndex that is the observed date |
| 92 | + ''' |
| 93 | + return fancy_group_by(df, |
| 94 | + grouping_level=dt_col, |
| 95 | + aggregate_level=asof_col, |
| 96 | + method='last', |
| 97 | + max_=as_of) |
| 98 | + |
| 99 | + |
| 100 | +# ----------------------- Insert/Append ---------------------------- # |
| 101 | + |
| 102 | + |
| 103 | +def multi_index_insert_row(df, index_row, values_row): |
| 104 | + """ Return a new dataframe with a row inserted for a multi-index dataframe. |
| 105 | + This will sort the rows according to the ordered multi-index levels. |
| 106 | + """ |
| 107 | + row_index = pd.MultiIndex(levels=[[i] for i in index_row], |
| 108 | + labels=[[0] for i in index_row]) |
| 109 | + row = pd.DataFrame(values_row, index=row_index, columns=df.columns) |
| 110 | + df = pd.concat((df, row)) |
| 111 | + if df.index.lexsort_depth == len(index_row) and df.index[-2] < df.index[-1]: |
| 112 | + # We've just appended a row to an already-sorted dataframe |
| 113 | + return df |
| 114 | + # The df wasn't sorted or the row has to be put in the middle somewhere |
| 115 | + return df.sortlevel() |
| 116 | + |
| 117 | + |
| 118 | +def insert_at(df, sample_date, values): |
| 119 | + """ Insert some values into a bi-temporal dataframe. |
| 120 | + This is like what would happen when we get a price correction. |
| 121 | + """ |
| 122 | + observed_dt = dt(datetime.now()) |
| 123 | + return multi_index_insert_row(df, [sample_date, observed_dt], values) |
0 commit comments