我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pandas.Period()。
def test_write_points_from_dataframe_with_period_index(self): dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[pd.Period('1970-01-01'), pd.Period('1970-01-02')], columns=["column_one", "column_two", "column_three"]) expected = ( b"foo column_one=\"1\",column_two=1i,column_three=1.0 0\n" b"foo column_one=\"2\",column_two=2i,column_three=2.0 " b"86400000000000\n" ) with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/write", status_code=204) cli = DataFrameClient(database='db') cli.write_points(dataframe, "foo") self.assertEqual(m.last_request.body, expected)
def test_write_points_from_dataframe_with_period_index(self): dataframe = pd.DataFrame(data=[["1", 1, 1.0], ["2", 2, 2.0]], index=[pd.Period('1970-01-01'), pd.Period('1970-01-02')], columns=["column_one", "column_two", "column_three"]) points = [ { "points": [ ["1", 1, 1.0, 0], ["2", 2, 2.0, 86400] ], "name": "foo", "columns": ["column_one", "column_two", "column_three", "time"] } ] with requests_mock.Mocker() as m: m.register_uri(requests_mock.POST, "http://localhost:8086/db/db/series") cli = DataFrameClient(database='db') cli.write_points({"foo": dataframe}) self.assertListEqual(json.loads(m.last_request.body), points)
def test_special_holidays(self): # 9/11 # Sept 11, 12, 13, 14 2001 self.assertNotIn(pd.Period("9/11/2001"), self.calendar.all_sessions) self.assertNotIn(pd.Period("9/12/2001"), self.calendar.all_sessions) self.assertNotIn(pd.Period("9/13/2001"), self.calendar.all_sessions) self.assertNotIn(pd.Period("9/14/2001"), self.calendar.all_sessions) # Hurricane Sandy # Oct 29, 30 2012 self.assertNotIn(pd.Period("10/29/2012"), self.calendar.all_sessions) self.assertNotIn(pd.Period("10/30/2012"), self.calendar.all_sessions) # various national days of mourning # Gerald Ford - 1/2/2007 self.assertNotIn(pd.Period("1/2/2007"), self.calendar.all_sessions) # Ronald Reagan - 6/11/2004 self.assertNotIn(pd.Period("6/11/2004"), self.calendar.all_sessions) # Richard Nixon - 4/27/1994 self.assertNotIn(pd.Period("4/27/1994"), self.calendar.all_sessions)
def test_period_cons_nat(self): p = Period('NaT', freq='M') self.assertEqual(p.ordinal, tslib.iNaT) self.assertEqual(p.freq, 'M') self.assertEqual((p + 1).ordinal, tslib.iNaT) p = Period('nat', freq='W-SUN') self.assertEqual(p.ordinal, tslib.iNaT) self.assertEqual(p.freq, 'W-SUN') self.assertEqual((p + 1).ordinal, tslib.iNaT) p = Period(tslib.iNaT, freq='D') self.assertEqual(p.ordinal, tslib.iNaT) self.assertEqual(p.freq, 'D') self.assertEqual((p + 1).ordinal, tslib.iNaT) p = Period(tslib.iNaT, freq='3D') self.assertEqual(p.ordinal, tslib.iNaT) self.assertEqual(p.freq, offsets.Day(3)) self.assertEqual(p.freqstr, '3D') self.assertEqual((p + 1).ordinal, tslib.iNaT) self.assertRaises(ValueError, Period, 'NaT')
def test_timestamp_tz_arg_dateutil(self): from pandas.tslib import _dateutil_gettz as gettz from pandas.tslib import maybe_get_tz for case in ['dateutil/Europe/Brussels', 'dateutil/Asia/Tokyo', 'dateutil/US/Pacific']: p = Period('1/1/2005', freq='M').to_timestamp( tz=maybe_get_tz(case)) exp = Timestamp('1/1/2005', tz='UTC').tz_convert(case) self.assertEqual(p, exp) self.assertEqual(p.tz, gettz(case.split('/', 1)[1])) self.assertEqual(p.tz, exp.tz) p = Period('1/1/2005', freq='M').to_timestamp(freq='3H', tz=maybe_get_tz(case)) exp = Timestamp('1/1/2005', tz='UTC').tz_convert(case) self.assertEqual(p, exp) self.assertEqual(p.tz, gettz(case.split('/', 1)[1])) self.assertEqual(p.tz, exp.tz)
def test_properties_daily(self): # Test properties on Periods with daily frequency. b_date = Period(freq='B', year=2007, month=1, day=1) # assert_equal(b_date.year, 2007) assert_equal(b_date.quarter, 1) assert_equal(b_date.month, 1) assert_equal(b_date.day, 1) assert_equal(b_date.weekday, 0) assert_equal(b_date.dayofyear, 1) assert_equal(b_date.days_in_month, 31) assert_equal(Period(freq='B', year=2012, month=2, day=1).days_in_month, 29) # d_date = Period(freq='D', year=2007, month=1, day=1) # assert_equal(d_date.year, 2007) assert_equal(d_date.quarter, 1) assert_equal(d_date.month, 1) assert_equal(d_date.day, 1) assert_equal(d_date.weekday, 0) assert_equal(d_date.dayofyear, 1) assert_equal(d_date.days_in_month, 31) assert_equal(Period(freq='D', year=2012, month=2, day=1).days_in_month, 29)
def test_properties_hourly(self): # Test properties on Periods with hourly frequency. h_date1 = Period(freq='H', year=2007, month=1, day=1, hour=0) h_date2 = Period(freq='2H', year=2007, month=1, day=1, hour=0) for h_date in [h_date1, h_date2]: assert_equal(h_date.year, 2007) assert_equal(h_date.quarter, 1) assert_equal(h_date.month, 1) assert_equal(h_date.day, 1) assert_equal(h_date.weekday, 0) assert_equal(h_date.dayofyear, 1) assert_equal(h_date.hour, 0) assert_equal(h_date.days_in_month, 31) assert_equal(Period(freq='H', year=2012, month=2, day=1, hour=0).days_in_month, 29)
def test_constructor_corner(self): expected = Period('2007-01', freq='2M') self.assertEqual(Period(year=2007, month=1, freq='2M'), expected) self.assertRaises(ValueError, Period, datetime.now()) self.assertRaises(ValueError, Period, datetime.now().date()) self.assertRaises(ValueError, Period, 1.6, freq='D') self.assertRaises(ValueError, Period, ordinal=1.6, freq='D') self.assertRaises(ValueError, Period, ordinal=2, value=1, freq='D') self.assertRaises(ValueError, Period) self.assertRaises(ValueError, Period, month=1) p = Period('2007-01-01', freq='D') result = Period(p, freq='A') exp = Period('2007', freq='A') self.assertEqual(result, exp)
def test_constructor_infer_freq(self): p = Period('2007-01-01') self.assertEqual(p.freq, 'D') p = Period('2007-01-01 07') self.assertEqual(p.freq, 'H') p = Period('2007-01-01 07:10') self.assertEqual(p.freq, 'T') p = Period('2007-01-01 07:10:15') self.assertEqual(p.freq, 'S') p = Period('2007-01-01 07:10:15.123') self.assertEqual(p.freq, 'L') p = Period('2007-01-01 07:10:15.123000') self.assertEqual(p.freq, 'L') p = Period('2007-01-01 07:10:15.123400') self.assertEqual(p.freq, 'U')
def test_slice_with_negative_step(self): ts = Series(np.arange(20), period_range('2014-01', periods=20, freq='M')) SLC = pd.IndexSlice def assert_slices_equivalent(l_slc, i_slc): assert_series_equal(ts[l_slc], ts.iloc[i_slc]) assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc]) assert_series_equal(ts.ix[l_slc], ts.iloc[i_slc]) assert_slices_equivalent(SLC[Period('2014-10')::-1], SLC[9::-1]) assert_slices_equivalent(SLC['2014-10'::-1], SLC[9::-1]) assert_slices_equivalent(SLC[:Period('2014-10'):-1], SLC[:8:-1]) assert_slices_equivalent(SLC[:'2014-10':-1], SLC[:8:-1]) assert_slices_equivalent(SLC['2015-02':'2014-10':-1], SLC[13:8:-1]) assert_slices_equivalent(SLC[Period('2015-02'):Period('2014-10'):-1], SLC[13:8:-1]) assert_slices_equivalent(SLC['2015-02':Period('2014-10'):-1], SLC[13:8:-1]) assert_slices_equivalent(SLC[Period('2015-02'):'2014-10':-1], SLC[13:8:-1]) assert_slices_equivalent(SLC['2014-10':'2015-02':-1], SLC[:0])
def test_dti_to_period(self): dti = DatetimeIndex(start='1/1/2005', end='12/1/2005', freq='M') pi1 = dti.to_period() pi2 = dti.to_period(freq='D') pi3 = dti.to_period(freq='3D') self.assertEqual(pi1[0], Period('Jan 2005', freq='M')) self.assertEqual(pi2[0], Period('1/31/2005', freq='D')) self.assertEqual(pi3[0], Period('1/31/2005', freq='3D')) self.assertEqual(pi1[-1], Period('Nov 2005', freq='M')) self.assertEqual(pi2[-1], Period('11/30/2005', freq='D')) self.assertEqual(pi3[-1], Period('11/30/2005', freq='3D')) tm.assert_index_equal(pi1, period_range('1/1/2005', '11/1/2005', freq='M')) tm.assert_index_equal(pi2, period_range('1/1/2005', '11/1/2005', freq='M').asfreq('D')) tm.assert_index_equal(pi3, period_range('1/1/2005', '11/1/2005', freq='M').asfreq('3D'))
def test_searchsorted(self): for freq in ['D', '2D']: pidx = pd.PeriodIndex(['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04', '2014-01-05'], freq=freq) p1 = pd.Period('2014-01-01', freq=freq) self.assertEqual(pidx.searchsorted(p1), 0) p2 = pd.Period('2014-01-04', freq=freq) self.assertEqual(pidx.searchsorted(p2), 3) msg = "Input has different freq=H from PeriodIndex" with self.assertRaisesRegexp(ValueError, msg): pidx.searchsorted(pd.Period('2014-01-01', freq='H')) msg = "Input has different freq=5D from PeriodIndex" with self.assertRaisesRegexp(ValueError, msg): pidx.searchsorted(pd.Period('2014-01-01', freq='5D'))
def test_negone_ordinals(self): freqs = ['A', 'M', 'Q', 'D', 'H', 'T', 'S'] period = Period(ordinal=-1, freq='D') for freq in freqs: repr(period.asfreq(freq)) for freq in freqs: period = Period(ordinal=-1, freq=freq) repr(period) self.assertEqual(period.year, 1969) period = Period(ordinal=-1, freq='B') repr(period) period = Period(ordinal=-1, freq='W') repr(period)
def test_fillna_period(self): # GH 11343 idx = pd.PeriodIndex( ['2011-01-01 09:00', pd.NaT, '2011-01-01 11:00'], freq='H') exp = pd.PeriodIndex( ['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00' ], freq='H') self.assert_index_equal( idx.fillna(pd.Period('2011-01-01 10:00', freq='H')), exp) exp = pd.Index([pd.Period('2011-01-01 09:00', freq='H'), 'x', pd.Period('2011-01-01 11:00', freq='H')], dtype=object) self.assert_index_equal(idx.fillna('x'), exp) with tm.assertRaisesRegexp( ValueError, 'Input has different freq=D from PeriodIndex\\(freq=H\\)'): idx.fillna(pd.Period('2011-01-01', freq='D'))
def test_abc_types(self): self.assertIsInstance(pd.Index(['a', 'b', 'c']), com.ABCIndex) self.assertIsInstance(pd.Int64Index([1, 2, 3]), com.ABCInt64Index) self.assertIsInstance(pd.Float64Index([1, 2, 3]), com.ABCFloat64Index) self.assertIsInstance(self.multi_index, com.ABCMultiIndex) self.assertIsInstance(self.datetime_index, com.ABCDatetimeIndex) self.assertIsInstance(self.timedelta_index, com.ABCTimedeltaIndex) self.assertIsInstance(self.period_index, com.ABCPeriodIndex) self.assertIsInstance(self.categorical_df.index, com.ABCCategoricalIndex) self.assertIsInstance(pd.Index(['a', 'b', 'c']), com.ABCIndexClass) self.assertIsInstance(pd.Int64Index([1, 2, 3]), com.ABCIndexClass) self.assertIsInstance(pd.Series([1, 2, 3]), com.ABCSeries) self.assertIsInstance(self.df, com.ABCDataFrame) self.assertIsInstance(self.df.to_panel(), com.ABCPanel) self.assertIsInstance(self.sparse_series, com.ABCSparseSeries) self.assertIsInstance(self.sparse_array, com.ABCSparseArray) self.assertIsInstance(self.categorical, com.ABCCategorical) self.assertIsInstance(pd.Period('2012', freq='A-DEC'), com.ABCPeriod)
def test_ops(self): for op in ['max', 'min']: for o in self.objs: result = getattr(o, op)() if not isinstance(o, PeriodIndex): expected = getattr(o.values, op)() else: expected = pd.Period(ordinal=getattr(o.values, op)(), freq=o.freq) try: self.assertEqual(result, expected) except TypeError: # comparing tz-aware series with np.array results in # TypeError expected = expected.astype('M8[ns]').astype('int64') self.assertEqual(result.value, expected)
def test_reset_index_period(self): # GH 7746 idx = pd.MultiIndex.from_product([pd.period_range('20130101', periods=3, freq='M'), ['a', 'b', 'c']], names=['month', 'feature']) df = pd.DataFrame(np.arange(9, dtype='int64') .reshape(-1, 1), index=idx, columns=['a']) expected = pd.DataFrame({ 'month': ([pd.Period('2013-01', freq='M')] * 3 + [pd.Period('2013-02', freq='M')] * 3 + [pd.Period('2013-03', freq='M')] * 3), 'feature': ['a', 'b', 'c'] * 3, 'a': np.arange(9, dtype='int64') }, columns=['month', 'feature', 'a']) assert_frame_equal(df.reset_index(), expected)
def agg_by_project(timesheet, date1=None, date2=None, freq=None): """ Slice the given timesheet by the given dates then aggregate total duration by project. If a Pandas frequency string is given (e.g. 'W' for calendar week), then resample by that frequency and then aggregate duration by project. Return a data frame with the columns: - ``'start_date'``: start date of the time period corresponding to the given frequency, or the first date in the sliced timesheet - ``'end_date'``: end date of the time period corresponding to the given frequency, or the last date in the sliced timesheet - ``'project'`` - ``'duration'``: total duration on project in period """ f = slice_by_dates(timesheet, date1, date2) if freq is not None: f = f.groupby('project').apply( lambda x: x.set_index('date')[['duration']].resample(freq ).sum().fillna(0)).reset_index() f = f[['date', 'project', 'duration']].sort_values( 'date') f['period'] = f['date'].map(lambda x: pd.Period(x, freq)) f['start_date'] = f['period'].map(lambda x: x.start_time) f['end_date'] = f['period'].map(lambda x: x.end_time) else: start_date, end_date = f['date'].min(), f['date'].max() f = f.groupby('project').agg({'duration': np.sum} ).reset_index() f['start_date'] = start_date f['end_date'] = end_date return f[['start_date', 'end_date', 'project', 'duration']].copy() #--------------------------------------- # Billing #---------------------------------------
def get_index(ds): """Converts the index to a DatetimeIndex""" v = [pd.Period(k["id"]).start_time for k in ds["structure"]["dimensions"]["observation"][0]["values"]] idx = pd.DatetimeIndex(v) idx.name = "d" return idx
def test_conversion(self): rs = self.pc.convert(['2012-1-1'], None, self.axis)[0] xp = Period('2012-1-1').ordinal self.assertEqual(rs, xp) rs = self.pc.convert('2012-1-1', None, self.axis) self.assertEqual(rs, xp) rs = self.pc.convert([date(2012, 1, 1)], None, self.axis)[0] self.assertEqual(rs, xp) rs = self.pc.convert(date(2012, 1, 1), None, self.axis) self.assertEqual(rs, xp) rs = self.pc.convert([Timestamp('2012-1-1')], None, self.axis)[0] self.assertEqual(rs, xp) rs = self.pc.convert(Timestamp('2012-1-1'), None, self.axis) self.assertEqual(rs, xp) # FIXME # rs = self.pc.convert(np.datetime64('2012-01-01'), None, self.axis) # self.assertEqual(rs, xp) # # rs = self.pc.convert(np.datetime64('2012-01-01 00:00:00+00:00'), # None, self.axis) # self.assertEqual(rs, xp) # # rs = self.pc.convert(np.array([ # np.datetime64('2012-01-01 00:00:00+00:00'), # np.datetime64('2012-01-02 00:00:00+00:00')]), None, self.axis) # self.assertEqual(rs[0], xp)
def test_asobject_tolist(self): idx = pd.period_range(start='2013-01-01', periods=4, freq='M', name='idx') expected_list = [pd.Period('2013-01-31', freq='M'), pd.Period('2013-02-28', freq='M'), pd.Period('2013-03-31', freq='M'), pd.Period('2013-04-30', freq='M')] expected = pd.Index(expected_list, dtype=object, name='idx') result = idx.asobject self.assertTrue(isinstance(result, Index)) self.assertEqual(result.dtype, object) self.assertTrue(result.equals(expected)) self.assertEqual(result.name, expected.name) self.assertEqual(idx.tolist(), expected_list) idx = PeriodIndex(['2013-01-01', '2013-01-02', 'NaT', '2013-01-04'], freq='D', name='idx') expected_list = [pd.Period('2013-01-01', freq='D'), pd.Period('2013-01-02', freq='D'), pd.Period('NaT', freq='D'), pd.Period('2013-01-04', freq='D')] expected = pd.Index(expected_list, dtype=object, name='idx') result = idx.asobject self.assertTrue(isinstance(result, Index)) self.assertEqual(result.dtype, object) for i in [0, 1, 3]: self.assertTrue(result[i], expected[i]) self.assertTrue(result[2].ordinal, pd.tslib.iNaT) self.assertTrue(result[2].freq, 'D') self.assertEqual(result.name, expected.name) result_list = idx.tolist() for i in [0, 1, 3]: self.assertTrue(result_list[i], expected_list[i]) self.assertTrue(result_list[2].ordinal, pd.tslib.iNaT) self.assertTrue(result_list[2].freq, 'D')
def test_minmax(self): # monotonic idx1 = pd.PeriodIndex([pd.NaT, '2011-01-01', '2011-01-02', '2011-01-03'], freq='D') self.assertTrue(idx1.is_monotonic) # non-monotonic idx2 = pd.PeriodIndex(['2011-01-01', pd.NaT, '2011-01-03', '2011-01-02', pd.NaT], freq='D') self.assertFalse(idx2.is_monotonic) for idx in [idx1, idx2]: self.assertEqual(idx.min(), pd.Period('2011-01-01', freq='D')) self.assertEqual(idx.max(), pd.Period('2011-01-03', freq='D')) self.assertEqual(idx1.argmin(), 1) self.assertEqual(idx2.argmin(), 0) self.assertEqual(idx1.argmax(), 3) self.assertEqual(idx2.argmax(), 2) for op in ['min', 'max']: # Return NaT obj = PeriodIndex([], freq='M') result = getattr(obj, op)() self.assertEqual(result.ordinal, tslib.iNaT) self.assertEqual(result.freq, 'M') obj = PeriodIndex([pd.NaT], freq='M') result = getattr(obj, op)() self.assertEqual(result.ordinal, tslib.iNaT) self.assertEqual(result.freq, 'M') obj = PeriodIndex([pd.NaT, pd.NaT, pd.NaT], freq='M') result = getattr(obj, op)() self.assertEqual(result.ordinal, tslib.iNaT) self.assertEqual(result.freq, 'M')
def test_period_cons_quarterly(self): # bugs in scikits.timeseries for month in MONTHS: freq = 'Q-%s' % month exp = Period('1989Q3', freq=freq) self.assertIn('1989Q3', str(exp)) stamp = exp.to_timestamp('D', how='end') p = Period(stamp, freq=freq) self.assertEqual(p, exp) stamp = exp.to_timestamp('3D', how='end') p = Period(stamp, freq=freq) self.assertEqual(p, exp)
def test_period_cons_annual(self): # bugs in scikits.timeseries for month in MONTHS: freq = 'A-%s' % month exp = Period('1989', freq=freq) stamp = exp.to_timestamp('D', how='end') + timedelta(days=30) p = Period(stamp, freq=freq) self.assertEqual(p, exp + 1)
def test_period_cons_weekly(self): for num in range(10, 17): daystr = '2011-02-%d' % num for day in DAYS: freq = 'W-%s' % day result = Period(daystr, freq=freq) expected = Period(daystr, freq='D').asfreq(freq) self.assertEqual(result, expected)
def test_period_cons_mult(self): p1 = Period('2011-01', freq='3M') p2 = Period('2011-01', freq='M') self.assertEqual(p1.ordinal, p2.ordinal) self.assertEqual(p1.freq, offsets.MonthEnd(3)) self.assertEqual(p1.freqstr, '3M') self.assertEqual(p2.freq, offsets.MonthEnd()) self.assertEqual(p2.freqstr, 'M') result = p1 + 1 self.assertEqual(result.ordinal, (p2 + 3).ordinal) self.assertEqual(result.freq, p1.freq) self.assertEqual(result.freqstr, '3M') result = p1 - 1 self.assertEqual(result.ordinal, (p2 - 3).ordinal) self.assertEqual(result.freq, p1.freq) self.assertEqual(result.freqstr, '3M') msg = ('Frequency must be positive, because it' ' represents span: -3M') with tm.assertRaisesRegexp(ValueError, msg): Period('2011-01', freq='-3M') msg = ('Frequency must be positive, because it' ' represents span: 0M') with tm.assertRaisesRegexp(ValueError, msg): Period('2011-01', freq='0M')
def test_timestamp_tz_arg_dateutil_from_string(self): from pandas.tslib import _dateutil_gettz as gettz p = Period('1/1/2005', freq='M').to_timestamp(tz='dateutil/Europe/Brussels') self.assertEqual(p.tz, gettz('Europe/Brussels'))
def test_timestamp_nat_tz(self): t = Period('NaT', freq='M').to_timestamp() self.assertTrue(t is tslib.NaT) t = Period('NaT', freq='M').to_timestamp(tz='Asia/Tokyo') self.assertTrue(t is tslib.NaT)
def test_timestamp_mult(self): p = pd.Period('2011-01', freq='M') self.assertEqual(p.to_timestamp(how='S'), pd.Timestamp('2011-01-01')) self.assertEqual(p.to_timestamp(how='E'), pd.Timestamp('2011-01-31')) p = pd.Period('2011-01', freq='3M') self.assertEqual(p.to_timestamp(how='S'), pd.Timestamp('2011-01-01')) self.assertEqual(p.to_timestamp(how='E'), pd.Timestamp('2011-03-31'))
def test_timestamp_nat_mult(self): for freq in ['M', '3M']: p = pd.Period('NaT', freq=freq) self.assertTrue(p.to_timestamp(how='S') is pd.NaT) self.assertTrue(p.to_timestamp(how='E') is pd.NaT)
def test_repr(self): p = Period('Jan-2000') self.assertIn('2000-01', repr(p)) p = Period('2000-12-15') self.assertIn('2000-12-15', repr(p))
def test_repr_nat(self): p = Period('nat', freq='M') self.assertIn(repr(tslib.NaT), repr(p))
def test_millisecond_repr(self): p = Period('2000-01-01 12:15:02.123') self.assertEqual("Period('2000-01-01 12:15:02.123', 'L')", repr(p))
def test_microsecond_repr(self): p = Period('2000-01-01 12:15:02.123567') self.assertEqual("Period('2000-01-01 12:15:02.123567', 'U')", repr(p))
def test_strftime(self): p = Period('2000-1-1 12:34:12', freq='S') res = p.strftime('%Y-%m-%d %H:%M:%S') self.assertEqual(res, '2000-01-01 12:34:12') tm.assertIsInstance(res, text_type) # GH3363
def test_start_time(self): freq_lst = ['A', 'Q', 'M', 'D', 'H', 'T', 'S'] xp = datetime(2012, 1, 1) for f in freq_lst: p = Period('2012', freq=f) self.assertEqual(p.start_time, xp) self.assertEqual(Period('2012', freq='B').start_time, datetime(2012, 1, 2)) self.assertEqual(Period('2012', freq='W').start_time, datetime(2011, 12, 26)) p = Period('NaT', freq='W') self.assertTrue(p.start_time is tslib.NaT)
def test_end_time(self): p = Period('2012', freq='A') def _ex(*args): return Timestamp(Timestamp(datetime(*args)).value - 1) xp = _ex(2013, 1, 1) self.assertEqual(xp, p.end_time) p = Period('2012', freq='Q') xp = _ex(2012, 4, 1) self.assertEqual(xp, p.end_time) p = Period('2012', freq='M') xp = _ex(2012, 2, 1) self.assertEqual(xp, p.end_time) p = Period('2012', freq='D') xp = _ex(2012, 1, 2) self.assertEqual(xp, p.end_time) p = Period('2012', freq='H') xp = _ex(2012, 1, 1, 1) self.assertEqual(xp, p.end_time) p = Period('2012', freq='B') xp = _ex(2012, 1, 3) self.assertEqual(xp, p.end_time) p = Period('2012', freq='W') xp = _ex(2012, 1, 2) self.assertEqual(xp, p.end_time) # Test for GH 11738 p = Period('2012', freq='15D') xp = _ex(2012, 1, 16) self.assertEqual(xp, p.end_time) p = Period('NaT', freq='W') self.assertTrue(p.end_time is tslib.NaT)
def test_anchor_week_end_time(self): def _ex(*args): return Timestamp(Timestamp(datetime(*args)).value - 1) p = Period('2013-1-1', 'W-SAT') xp = _ex(2013, 1, 6) self.assertEqual(p.end_time, xp)
def test_properties_annually(self): # Test properties on Periods with annually frequency. a_date = Period(freq='A', year=2007) assert_equal(a_date.year, 2007)
def test_properties_quarterly(self): # Test properties on Periods with daily frequency. qedec_date = Period(freq="Q-DEC", year=2007, quarter=1) qejan_date = Period(freq="Q-JAN", year=2007, quarter=1) qejun_date = Period(freq="Q-JUN", year=2007, quarter=1) # for x in range(3): for qd in (qedec_date, qejan_date, qejun_date): assert_equal((qd + x).qyear, 2007) assert_equal((qd + x).quarter, x + 1)
def test_properties_weekly(self): # Test properties on Periods with daily frequency. w_date = Period(freq='W', year=2007, month=1, day=7) # assert_equal(w_date.year, 2007) assert_equal(w_date.quarter, 1) assert_equal(w_date.month, 1) assert_equal(w_date.week, 1) assert_equal((w_date - 1).week, 52) assert_equal(w_date.days_in_month, 31) assert_equal(Period(freq='W', year=2012, month=2, day=1).days_in_month, 29)
def test_properties_weekly_legacy(self): # Test properties on Periods with daily frequency. with tm.assert_produces_warning(FutureWarning): w_date = Period(freq='WK', year=2007, month=1, day=7) # assert_equal(w_date.year, 2007) assert_equal(w_date.quarter, 1) assert_equal(w_date.month, 1) assert_equal(w_date.week, 1) assert_equal((w_date - 1).week, 52) assert_equal(w_date.days_in_month, 31) with tm.assert_produces_warning(FutureWarning): exp = Period(freq='WK', year=2012, month=2, day=1) assert_equal(exp.days_in_month, 29)
def test_properties_minutely(self): # Test properties on Periods with minutely frequency. t_date = Period(freq='Min', year=2007, month=1, day=1, hour=0, minute=0) # assert_equal(t_date.quarter, 1) assert_equal(t_date.month, 1) assert_equal(t_date.day, 1) assert_equal(t_date.weekday, 0) assert_equal(t_date.dayofyear, 1) assert_equal(t_date.hour, 0) assert_equal(t_date.minute, 0) assert_equal(t_date.days_in_month, 31) assert_equal(Period(freq='D', year=2012, month=2, day=1, hour=0, minute=0).days_in_month, 29)
def test_properties_nat(self): p_nat = Period('NaT', freq='M') t_nat = pd.Timestamp('NaT') # confirm Period('NaT') work identical with Timestamp('NaT') for f in ['year', 'month', 'day', 'hour', 'minute', 'second', 'week', 'dayofyear', 'quarter', 'days_in_month']: self.assertTrue(np.isnan(getattr(p_nat, f))) self.assertTrue(np.isnan(getattr(t_nat, f))) for f in ['weekofyear', 'dayofweek', 'weekday', 'qyear']: self.assertTrue(np.isnan(getattr(p_nat, f)))
def test_pnow(self): dt = datetime.now() val = period.pnow('D') exp = Period(dt, freq='D') self.assertEqual(val, exp) val2 = period.pnow('2D') exp2 = Period(dt, freq='2D') self.assertEqual(val2, exp2) self.assertEqual(val.ordinal, val2.ordinal) self.assertEqual(val.ordinal, exp2.ordinal)
def test_asfreq_MS(self): initial = Period("2013") self.assertEqual(initial.asfreq(freq="M", how="S"), Period('2013-01', 'M')) self.assertRaises(ValueError, initial.asfreq, freq="MS", how="S") tm.assertRaisesRegexp(ValueError, "Unknown freqstr: MS", pd.Period, '2013-01', 'MS') self.assertTrue(_period_code_map.get("MS") is None)
def test_asfreq_nat(self): p = Period('NaT', freq='A') result = p.asfreq('M') self.assertEqual(result.ordinal, tslib.iNaT) self.assertEqual(result.freq, 'M')
def test_asfreq_mult_nat(self): # normal freq to mult freq for p in [Period('NaT', freq='A'), Period('NaT', freq='3A'), Period('NaT', freq='2M'), Period('NaT', freq='3D')]: for freq in ['3A', offsets.YearEnd(3)]: result = p.asfreq(freq) expected = Period('NaT', freq='3A') self.assertEqual(result.ordinal, pd.tslib.iNaT) self.assertEqual(result.freq, expected.freq) result = p.asfreq(freq, how='S') expected = Period('NaT', freq='3A') self.assertEqual(result.ordinal, pd.tslib.iNaT) self.assertEqual(result.freq, expected.freq)
def test_constructor_use_start_freq(self): # GH #1118 p = Period('4/2/2012', freq='B') index = PeriodIndex(start=p, periods=10) expected = PeriodIndex(start='4/2/2012', periods=10, freq='B') self.assertTrue(index.equals(expected))
def test_constructor_field_arrays(self): # GH #1264 years = np.arange(1990, 2010).repeat(4)[2:-2] quarters = np.tile(np.arange(1, 5), 20)[2:-2] index = PeriodIndex(year=years, quarter=quarters, freq='Q-DEC') expected = period_range('1990Q3', '2009Q2', freq='Q-DEC') self.assertTrue(index.equals(expected)) index2 = PeriodIndex(year=years, quarter=quarters, freq='2Q-DEC') tm.assert_numpy_array_equal(index.asi8, index2.asi8) index = PeriodIndex(year=years, quarter=quarters) self.assertTrue(index.equals(expected)) years = [2007, 2007, 2007] months = [1, 2] self.assertRaises(ValueError, PeriodIndex, year=years, month=months, freq='M') self.assertRaises(ValueError, PeriodIndex, year=years, month=months, freq='2M') self.assertRaises(ValueError, PeriodIndex, year=years, month=months, freq='M', start=Period('2007-01', freq='M')) years = [2007, 2007, 2007] months = [1, 2, 3] idx = PeriodIndex(year=years, month=months, freq='M') exp = period_range('2007-01', periods=3, freq='M') self.assertTrue(idx.equals(exp))