Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API: Expanded resample #13961

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions doc/source/timeseries.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,28 @@ Furthermore, you can also specify multiple aggregation functions for each column
r.agg({'A' : ['sum','std'], 'B' : ['mean','std'] })


If a ``DataFrame`` does not have a ``DatetimeIndex``, but instead you want
to resample based on column in the frame, it can passed to the ``on`` keyword.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make it clear that the on (currently) still must be a datetimelike (so we of course accept PeriodIndex/TimedeltaIndex here as well (add tests if we don't have them for those as well)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use datetimelike rather than DatetimeIndex


.. ipython:: python

df = pd.DataFrame({'date': pd.date_range('2015-01-01', freq='W', periods=5),
'a': np.arange(5)},
index=pd.MultiIndex.from_arrays([
[1,2,3,4,5],
pd.date_range('2015-01-01', freq='W', periods=5)],
names=['v','d']))
df
df.resample('M', on='date').sum()

Similarly, if you instead want to resample by a level of ``MultiIndex``, its
name or location can be passed to the ``level`` keyword.

.. ipython:: python

df.resample(level='d').sum()


.. _timeseries.periods:

Time Span Representation
Expand Down
14 changes: 14 additions & 0 deletions doc/source/whatsnew/v0.19.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,20 @@ Other enhancements

pd.Timestamp(year=2012, month=1, day=1, hour=8, minute=30)

- the ``.resample()`` function now accepts a ``on=`` or ``level=`` parameter for resampling on a column or ``MultiIndex`` level (:issue:`13500`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

again would say datetimelike as well. Further I think the doc-string of .resample needs more specific wording (mentiioning datetimelike).

what we have now

Convenience method for frequency conversion and resampling of regular
time-series data.


.. ipython:: python

df = pd.DataFrame({'date': pd.date_range('2015-01-01', freq='W', periods=5),
'a': np.arange(5)},
index=pd.MultiIndex.from_arrays([
[1,2,3,4,5],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would add to the main docs a similar example

pd.date_range('2015-01-01', freq='W', periods=5)],
names=['v','d']))
df
df.resample('M', on='date').sum()
df.resample('M', level='d').sum()

- The ``pd.read_csv()`` with ``engine='python'`` has gained support for the ``decimal`` option (:issue:`12933`)
- The ``pd.read_csv()`` with ``engine='python'`` has gained support for the ``na_filter`` option (:issue:`13321`)
- The ``pd.read_csv()`` with ``engine='python'`` has gained support for the ``memory_map`` option (:issue:`13381`)
Expand Down
12 changes: 8 additions & 4 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4038,7 +4038,7 @@ def between_time(self, start_time, end_time, include_start=True,

def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,
label=None, convention='start', kind=None, loffset=None,
limit=None, base=0):
limit=None, base=0, on=None, level=None):
"""
Convenience method for frequency conversion and resampling of regular
time-series data.
Expand All @@ -4059,7 +4059,12 @@ def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,
For frequencies that evenly subdivide 1 day, the "origin" of the
aggregated intervals. For example, for '5min' frequency, base could
range from 0 through 4. Defaults to 0

on : string, optional
For a DataFrame, column to use for resampling, rather than
the index
level : string or int, optional
For a MultiIndex, level (name or number) to use for
resampling

To learn more about the offset strings, please see `this link
<http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__.
Expand Down Expand Up @@ -4164,12 +4169,11 @@ def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,
"""
from pandas.tseries.resample import (resample,
_maybe_process_deprecations)

axis = self._get_axis_number(axis)
r = resample(self, freq=rule, label=label, closed=closed,
axis=axis, kind=kind, loffset=loffset,
convention=convention,
base=base)
base=base, key=on, level=level)
return _maybe_process_deprecations(r,
how=how,
fill_method=fill_method,
Expand Down
69 changes: 58 additions & 11 deletions pandas/tseries/tests/test_resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,20 +450,30 @@ def test_agg(self):
('r2', 'B', 'sum')])

def test_agg_misc(self):
# test with both a Resampler and a TimeGrouper
# test with all three Resampler apis and TimeGrouper

np.random.seed(1234)
df = pd.DataFrame(np.random.rand(10, 2),
columns=list('AB'),
index=pd.date_range('2010-01-01 09:00:00',
periods=10,
freq='s'))
freq='s',
name='date'))
df_col = df.reset_index()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you might be able to move this to Base as this is only testing DTI

df_mult = df_col.copy()
df_mult.index = pd.MultiIndex.from_arrays([range(10), df.index],
names=['index', 'date'])

r = df.resample('2s')
g = df.groupby(pd.Grouper(freq='2s'))
cases = [
r,
df_col.resample('2s', on='date'),
df_mult.resample('2s', level='date'),
df.groupby(pd.Grouper(freq='2s'))
]

# passed lambda
for t in [r, g]:
for t in cases:
result = t.agg({'A': np.sum,
'B': lambda x: np.std(x, ddof=1)})
rcustom = t['B'].apply(lambda x: np.std(x, ddof=1))
Expand All @@ -480,7 +490,7 @@ def test_agg_misc(self):
('result1', 'B'),
('result2', 'A'),
('result2', 'B')])
for t in [r, g]:
for t in cases:
result = t[['A', 'B']].agg(OrderedDict([('result1', np.sum),
('result2', np.mean)]))
assert_frame_equal(result, expected, check_like=True)
Expand All @@ -495,19 +505,19 @@ def test_agg_misc(self):
('A', 'std'),
('B', 'mean'),
('B', 'std')])
for t in [r, g]:
for t in cases:
result = t.agg(OrderedDict([('A', ['sum', 'std']),
('B', ['mean', 'std'])]))
assert_frame_equal(result, expected, check_like=True)

# equivalent of using a selection list / or not
for t in [r, g]:
result = g[['A', 'B']].agg({'A': ['sum', 'std'],
for t in cases:
result = t[['A', 'B']].agg({'A': ['sum', 'std'],
'B': ['mean', 'std']})
assert_frame_equal(result, expected, check_like=True)

# series like aggs
for t in [r, g]:
for t in cases:
result = t['A'].agg({'A': ['sum', 'std']})
expected = pd.concat([t['A'].sum(),
t['A'].std()],
Expand All @@ -528,9 +538,9 @@ def test_agg_misc(self):

# errors
# invalid names in the agg specification
for t in [r, g]:
for t in cases:
def f():
r[['A']].agg({'A': ['sum', 'std'],
t[['A']].agg({'A': ['sum', 'std'],
'B': ['mean', 'std']})

self.assertRaises(SpecificationError, f)
Expand Down Expand Up @@ -581,6 +591,43 @@ def test_agg_consistency(self):
result = r.agg({'r1': 'mean', 'r2': 'sum'})
assert_frame_equal(result, expected)

def test_api_validation(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

# GH 13500
dates = pd.date_range('2015-01-01', freq='W', periods=10)
df = pd.DataFrame({'date': dates,
'a': np.arange(10, dtype='int64')},
index=pd.MultiIndex.from_arrays([
np.arange(10),
dates], names=['v', 'd']))

exp_index = pd.date_range('2015-01-31', periods=3,
freq='M', name='date')
expected = pd.DataFrame({'a': [6, 22, 17]},
index=exp_index)

actual = df.resample('M', on='date').sum()
assert_frame_equal(actual, expected)

expected.index.name = 'd'
actual = df.resample('M', level='d').sum()
assert_frame_equal(actual, expected)

actual = df.resample('M', level=1).sum()
assert_frame_equal(actual, expected)

# non DatetimeIndex
with tm.assertRaises(TypeError):
df.resample('M', level='v')

with tm.assertRaises(ValueError):
df.resample('M', on='date', level='d')

with tm.assertRaises(TypeError):
df.resample('M', on=['a', 'date'])

with tm.assertRaises(KeyError):
df.resample('M', level=['a', 'date'])


class Base(object):
"""
Expand Down