Skip to content

ENH: between_time, at_time accept axis parameter #21799

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

Merged
merged 11 commits into from
Nov 19, 2018
3 changes: 3 additions & 0 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ Other Enhancements
- :func:`to_timedelta` now supports iso-formated timedelta strings (:issue:`21877`)
- :class:`Series` and :class:`DataFrame` now support :class:`Iterable` in constructor (:issue:`2193`)
- :class:`DatetimeIndex` gained :attr:`DatetimeIndex.timetz` attribute. Returns local time with timezone information. (:issue:`21358`)
- :func:`~DataFrame.to_csv` and :func:`~DataFrame.to_json` now support ``compression='infer'`` to infer compression based on filename (:issue:`15008`)
Copy link
Contributor

Choose a reason for hiding this comment

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

looks like you picked up something extra here

- :func:`between_time` and :func:`at_time` now support an ``axis`` parameter (:issue: `8839`)
-

.. _whatsnew_0240.api_breaking:

Expand Down
31 changes: 25 additions & 6 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7013,7 +7013,7 @@ def asfreq(self, freq, method=None, how=None, normalize=False,
return asfreq(self, freq, method=method, how=how, normalize=normalize,
fill_value=fill_value)

def at_time(self, time, asof=False):
def at_time(self, time, asof=False, axis=None):
"""
Select values at particular time of day (e.g. 9:30AM).

Expand All @@ -7025,6 +7025,10 @@ def at_time(self, time, asof=False):
Parameters
----------
time : datetime.time or string
axis : int or string axis name, optional
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add a versionadded 0.24.0 here (and other new kwargs)


.. versionadded:: 0.24.0


Returns
-------
Expand Down Expand Up @@ -7054,14 +7058,20 @@ def at_time(self, time, asof=False):
DatetimeIndex.indexer_at_time : Get just the index locations for
values at particular time of the day
"""
if axis is None:
axis = self._stat_axis_number
axis = self._get_axis_number(axis)

index = self._get_axis(axis)
try:
indexer = self.index.indexer_at_time(time, asof=asof)
return self._take(indexer)
indexer = index.indexer_at_time(time, asof=asof)
except AttributeError:
raise TypeError('Index must be DatetimeIndex')

return self._take(indexer, axis=axis)

def between_time(self, start_time, end_time, include_start=True,
include_end=True):
include_end=True, axis=None):
"""
Select values between particular times of the day (e.g., 9:00-9:30 AM).

Expand All @@ -7079,6 +7089,9 @@ def between_time(self, start_time, end_time, include_start=True,
end_time : datetime.time or string
include_start : boolean, default True
include_end : boolean, default True
axis : int or string axis name, optional
Copy link
Contributor

Choose a reason for hiding this comment

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

same


.. versionadded:: 0.24.0

Returns
-------
Expand Down Expand Up @@ -7116,14 +7129,20 @@ def between_time(self, start_time, end_time, include_start=True,
DatetimeIndex.indexer_between_time : Get just the index locations for
values between particular times of the day
"""
if axis is None:
axis = self._stat_axis_number
axis = self._get_axis_number(axis)

index = self._get_axis(axis)
try:
indexer = self.index.indexer_between_time(
indexer = index.indexer_between_time(
start_time, end_time, include_start=include_start,
include_end=include_end)
return self._take(indexer)
except AttributeError:
raise TypeError('Index must be DatetimeIndex')

return self._take(indexer, axis=axis)

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, on=None, level=None):
Expand Down
57 changes: 57 additions & 0 deletions pandas/tests/frame/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,23 @@ def test_at_time_raises(self):
with pytest.raises(TypeError): # index is not a DatetimeIndex
df.at_time('00:00')

@pytest.mark.parametrize('axis', ['index', 'columns', 0, 1])
Copy link
Contributor

Choose a reason for hiding this comment

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

just remove the paramerize, the axis is already defined

def test_at_time_axis(self, axis):
# issue 8839
rng = date_range('1/1/2000', '1/5/2000', freq='5min')
ts = DataFrame(np.random.randn(len(rng), len(rng)))
ts.index, ts.columns = rng, rng

indices = rng[(rng.hour == 9) & (rng.minute == 30) & (rng.second == 0)]

if axis in ['index', 0]:
expected = ts.loc[indices, :]
elif axis in ['columns', 1]:
expected = ts.loc[:, indices]

result = ts.at_time('9:30', axis=axis)
assert_frame_equal(result, expected)

def test_between_time(self):
rng = date_range('1/1/2000', '1/5/2000', freq='5min')
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
Expand Down Expand Up @@ -706,6 +723,46 @@ def test_between_time_raises(self):
with pytest.raises(TypeError): # index is not a DatetimeIndex
df.between_time(start_time='00:00', end_time='12:00')

@pytest.mark.parametrize('axis', [
Copy link
Contributor

Choose a reason for hiding this comment

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

also test for 0, 1

Copy link
Contributor

Choose a reason for hiding this comment

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

the new axis fixture will handle this, can you use that

Copy link
Contributor Author

Choose a reason for hiding this comment

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

which new axis fixture?

Copy link
Contributor

Choose a reason for hiding this comment

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

rebase in master and axis is available

Copy link
Contributor

Choose a reason for hiding this comment

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

why is this not just using the axis fixture?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I couldn't figure out what the axis fixture is. Is there documentation about this?

Copy link
Member

Choose a reason for hiding this comment

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

Here's the location of it. It just supplies the various arguments that are typically valid for an axis parameter

def axis(request):

(), ('index',), ('columns',), ('index', 'columns'),
(0, ), (1, ), (0, 1)])
def test_between_time_axis(self, axis):
# issue 8839
rng = date_range('1/1/2000', periods=100, freq='10min')
ts = DataFrame(np.random.randn(len(rng), len(rng)))
stime, etime = ('08:00:00', '09:00:00')
exp_len = 7

if 'index' in axis or 0 in axis:
ts.index = rng
assert len(ts.between_time(stime, etime)) == exp_len
assert len(ts.between_time(stime, etime, axis=0)) == exp_len

if 'columns' in axis or 1 in axis:
ts.columns = rng
selected = ts.between_time(stime, etime, axis=1).columns
assert len(selected) == exp_len

@pytest.mark.parametrize('axis', [
(), ('index',), ('columns',), ('index', 'columns'),
Copy link
Contributor

Choose a reason for hiding this comment

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

same, this is very werid

(0, ), (1, ), (0, 1)])
def test_between_time_axis_raises(self, axis):
# issue 8839
rng = date_range('1/1/2000', periods=100, freq='10min')
mask = np.arange(0, len(rng))
rand_data = np.random.randn(len(rng), len(rng))
ts = DataFrame(rand_data, index=rng, columns=rng)
stime, etime = ('08:00:00', '09:00:00')

if 'index' not in axis and 0 not in axis:
ts.index = mask
pytest.raises(TypeError, ts.between_time, stime, etime)
pytest.raises(TypeError, ts.between_time, stime, etime, axis=0)

if 'columns' not in axis and 1 not in axis:
ts.columns = mask
pytest.raises(TypeError, ts.between_time, stime, etime, axis=1)

def test_operation_on_NaT(self):
# Both NaT and Timestamp are in DataFrame.
df = pd.DataFrame({'foo': [pd.NaT, pd.NaT,
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/series/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,17 @@ def test_between_time_formats(self):
for time_string in strings:
assert len(ts.between_time(*time_string)) == expected_length

def test_between_time_axis(self):
# issue 8839
rng = date_range('1/1/2000', periods=100, freq='10min')
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add the issue number as a comment (to all new tests)

ts = Series(np.random.randn(len(rng)), index=rng)
stime, etime = ('08:00:00', '09:00:00')
expected_length = 7

assert len(ts.between_time(stime, etime)) == expected_length
assert len(ts.between_time(stime, etime, axis=0)) == expected_length
pytest.raises(ValueError, ts.between_time, stime, etime, axis=1)

def test_to_period(self):
from pandas.core.indexes.period import period_range

Expand Down