We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a0d05db commit 48d187dCopy full SHA for 48d187d
pandas/tseries/base.py
@@ -236,16 +236,25 @@ def __getitem__(self, key):
236
237
attribs = self._get_attributes_dict()
238
239
- freq = None
240
- if isinstance(key, slice):
241
- if self.freq is not None and key.step is not None:
242
- freq = key.step * self.freq
243
- else:
244
- freq = self.freq
+ is_period = isinstance(self, ABCPeriodIndex)
+ if is_period:
+ freq = self.freq
+ else:
+ freq = None
+ if isinstance(key, slice):
245
+ if self.freq is not None and key.step is not None:
246
+ freq = key.step * self.freq
247
248
249
+
250
attribs['freq'] = freq
251
252
result = getitem(key)
253
if result.ndim > 1:
254
+ # To support MPL which performs slicing with 2 dim
255
+ # even though it only has 1 dim by definition
256
257
+ return self._simple_new(result, **attribs)
258
return result
259
260
return self._simple_new(result, **attribs)
pandas/tseries/period.py
@@ -862,25 +862,6 @@ def _apply_meta(self, rawarr):
862
rawarr = PeriodIndex(rawarr, freq=self.freq)
863
return rawarr
864
865
- def __getitem__(self, key):
866
- getitem = self._data.__getitem__
867
- if is_scalar(key):
868
- val = getitem(key)
869
- return Period(ordinal=val, freq=self.freq)
870
871
- if com.is_bool_indexer(key):
872
- key = np.asarray(key)
873
-
874
- result = getitem(key)
875
- if result.ndim > 1:
876
- # MPL kludge
877
- # values = np.asarray(list(values), dtype=object)
878
- # return values.reshape(result.shape)
879
880
- return PeriodIndex(result, name=self.name, freq=self.freq)
881
882
883
884
def _format_native_types(self, na_rep=u('NaT'), date_format=None,
885
**kwargs):
886
pandas/tseries/tests/test_period.py
@@ -2060,8 +2060,23 @@ def test_getitem_ndim2(self):
2060
idx = period_range('2007-01', periods=3, freq='M')
2061
2062
result = idx[:, None]
2063
+ # MPL kludge, internally has incorrect shape
2064
tm.assertIsInstance(result, PeriodIndex)
2065
+ self.assertEqual(result.shape, (len(idx), 1))
2066
2067
+ def test_getitem_index(self):
2068
+ idx = period_range('2007-01', periods=10, freq='M', name='x')
2069
2070
+ result = idx[[1, 3, 5]]
2071
+ exp = pd.PeriodIndex(['2007-02', '2007-04', '2007-06'],
2072
+ freq='M', name='x')
2073
+ tm.assert_index_equal(result, exp)
2074
2075
+ result = idx[[True, True, False, False, False,
2076
+ True, True, False, False, False]]
2077
+ exp = pd.PeriodIndex(['2007-01', '2007-02', '2007-06', '2007-07'],
2078
2079
2080
2081
def test_getitem_partial(self):
2082
rng = period_range('2007-01', periods=50, freq='M')
0 commit comments