Skip to content

Fix inconsistency in Partial String Index with 'second' resolution #14856

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

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 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
10 changes: 4 additions & 6 deletions pandas/tseries/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -1293,14 +1293,12 @@ def _parsed_string_to_bounds(self, reso, parsed):

def _partial_date_slice(self, reso, parsed, use_lhs=True, use_rhs=True):
is_monotonic = self.is_monotonic
if ((reso in ['day', 'hour', 'minute'] and
not (self._resolution < Resolution.get_reso(reso) or
not is_monotonic)) or
(reso == 'second' and
not (self._resolution <= Resolution.RESO_SEC or
not is_monotonic))):
if (is_monotonic and reso in ['day', 'hour', 'minute', 'second'] and
self._resolution >= Resolution.get_reso(reso)):
# These resolution/monotonicity validations came from GH3931,
# GH3452 and GH2369.

# See also GH14826
raise KeyError

if reso == 'microsecond':
Expand Down
61 changes: 58 additions & 3 deletions pandas/tseries/tests/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,16 +266,15 @@ def test_indexing(self):
expected = ts['2013']
assert_series_equal(expected, ts)

# GH 3925, indexing with a seconds resolution string / datetime object
# GH14826, indexing with a seconds resolution string / datetime object
df = DataFrame(randn(5, 5),
columns=['open', 'high', 'low', 'close', 'volume'],
index=date_range('2012-01-02 18:01:00',
periods=5, tz='US/Central', freq='s'))
expected = df.loc[[df.index[2]]]
result = df['2012-01-02 18:01:02']
assert_frame_equal(result, expected)

# this is a single date, so will raise
self.assertRaises(KeyError, df.__getitem__, '2012-01-02 18:01:02', )
self.assertRaises(KeyError, df.__getitem__, df.index[2], )

def test_recreate_from_data(self):
Expand Down Expand Up @@ -4941,6 +4940,62 @@ def test_partial_slice_second_precision(self):
self.assertRaisesRegexp(KeyError, '2005-1-1 00:00:00',
lambda: s['2005-1-1 00:00:00'])

def test_partial_slicing_dataframe(self):
# GH14856
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 give a 1-2 lines about what are asserting here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. 67e6bab

# Test various combinations of string slicing
formats = ['%Y', '%Y-%m', '%Y-%m-%d', '%Y-%m-%d %H',
'%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S']
resolutions = ['year', 'month', 'day', 'hour', 'minute', 'second']
for rnum, resolution in enumerate(resolutions[2:], 2):
unit = Timedelta(1, resolution[0])
middate = datetime(2012, 1, 1, 0, 0, 0)
index = DatetimeIndex([middate - unit,
middate, middate + unit])
values = [1, 2, 3]
df = DataFrame({'a': values}, index, dtype=np.int64)
self.assertEqual(df.index.resolution, resolution)

# Timestamp with the same resolution as index
# Should be exact match for series and raise KeyError for Frame
for timestamp, expected in zip(index, values):
ts_string = timestamp.strftime(formats[rnum])
# make ts_string as precise as index
result = df['a'][ts_string]
self.assertIsInstance(result, np.int64)
self.assertEqual(result, expected)
self.assertRaises(KeyError, df.__getitem__, ts_string)

# Timestamp with resolution less precise than index
for fmt in formats[:rnum]:
for element, theslice in [[0, slice(None, 1)],
[1, slice(1, None)]]:
ts_string = index[element].strftime(fmt)
# Series should return slice
result = df['a'][ts_string]
expected = df['a'][theslice]
assert_series_equal(result, expected)

# Frame should return slice as well
result = df[ts_string]
expected = df[theslice]
assert_frame_equal(result, expected)

# Timestamp with resolution more precise than index
# Compatible with existing key
for fmt in formats[rnum + 1:]:
ts_string = index[1].strftime(fmt)
result = df['a'][ts_string]
self.assertIsInstance(result, np.int64)
self.assertEqual(result, 2)
self.assertRaises(KeyError, df.__getitem__, ts_string)

# Not compatible with existing key
for fmt, res in list(zip(formats, resolutions))[rnum + 1:]:
ts = index[1] + Timedelta(1, res[0])
ts_string = ts.strftime(fmt)
self.assertRaises(KeyError, df['a'].__getitem__, ts_string)
self.assertRaises(KeyError, df.__getitem__, ts_string)

def test_partial_slicing_with_multiindex(self):

# GH 4758
Expand Down