From eb0082741b124481918d99b341ca10a99fc31b47 Mon Sep 17 00:00:00 2001 From: Chang She Date: Wed, 21 Nov 2012 00:25:05 -0500 Subject: [PATCH] BUG: PeriodIndex as DataFrame column should box to Periods #2243 #2281 --- pandas/core/frame.py | 8 +++++++- pandas/tseries/tests/test_period.py | 15 ++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 44b31926f4e15..c82a6c7a9bfe3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2022,6 +2022,8 @@ def _sanitize_column(self, key, value): if not isinstance(value, np.ndarray): value = com._asarray_tuplesafe(value) + elif isinstance(value, PeriodIndex): + value = value.asobject else: value = value.copy() else: @@ -2699,7 +2701,11 @@ def _maybe_cast(values): lev_num = self.columns._get_level_number(col_level) name_lst[lev_num] = name name = tuple(name_lst) - new_obj.insert(0, name, _maybe_cast(self.index.values)) + if isinstance(self.index, PeriodIndex): + values = self.index.asobject + else: + values = self.index.values + new_obj.insert(0, name, _maybe_cast(values)) new_obj.index = new_index return new_obj diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py index 0938080064efb..dfa4b341d883f 100644 --- a/pandas/tseries/tests/test_period.py +++ b/pandas/tseries/tests/test_period.py @@ -15,7 +15,7 @@ from pandas import Timestamp from pandas.tseries.frequencies import MONTHS, DAYS from pandas.tseries.period import Period, PeriodIndex, period_range -from pandas.tseries.index import DatetimeIndex, date_range +from pandas.tseries.index import DatetimeIndex, date_range, Index from pandas.tseries.tools import to_datetime import pandas.tseries.period as pmod @@ -1300,6 +1300,19 @@ def test_as_frame_columns(self): ts = df['1/1/2000'] assert_series_equal(ts, df.ix[:, 0]) + def test_frame_setitem(self): + rng = period_range('1/1/2000', periods=5) + rng.name = 'index' + df = DataFrame(randn(5, 3), index=rng) + + df['Index'] = rng + rs = Index(df['Index']) + self.assert_(rs.equals(rng)) + + rs = df.reset_index().set_index('index') + self.assert_(isinstance(rs.index, PeriodIndex)) + self.assert_(rs.index.equals(rng)) + def test_nested_dict_frame_constructor(self): rng = period_range('1/1/2000', periods=5) df = DataFrame(randn(10, 5), columns=rng)