Python pandas.Period() Examples

The following are 30 code examples of pandas.Period(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pandas , or try the search function .
Example #1
Source File: test_apply.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_applymap_box(self):
        # ufunc will not be boxed. Same test cases as the test_map_box
        df = pd.DataFrame({'a': [pd.Timestamp('2011-01-01'),
                                 pd.Timestamp('2011-01-02')],
                           'b': [pd.Timestamp('2011-01-01', tz='US/Eastern'),
                                 pd.Timestamp('2011-01-02', tz='US/Eastern')],
                           'c': [pd.Timedelta('1 days'),
                                 pd.Timedelta('2 days')],
                           'd': [pd.Period('2011-01-01', freq='M'),
                                 pd.Period('2011-01-02', freq='M')]})

        result = df.applymap(lambda x: '{0}'.format(x.__class__.__name__))
        expected = pd.DataFrame({'a': ['Timestamp', 'Timestamp'],
                                 'b': ['Timestamp', 'Timestamp'],
                                 'c': ['Timedelta', 'Timedelta'],
                                 'd': ['Period', 'Period']})
        tm.assert_frame_equal(result, expected) 
Example #2
Source File: test_parameters.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
def test_parameter_array_indexed(simple_linear_model):
    """
    Test ArrayIndexedParameter

    """
    model = simple_linear_model
    A = np.arange(len(model.timestepper), dtype=np.float64)
    p = ArrayIndexedParameter(model, A)
    model.setup()
    # scenario indices (not used for this test)
    si = ScenarioIndex(0, np.array([0], dtype=np.int32))
    for v, ts in zip(A, model.timestepper):
        np.testing.assert_allclose(p.value(ts, si), v)

    # Now check that IndexError is raised if an out of bounds Timestep is given.
    ts = Timestep(pd.Period('2016-01-01', freq='1D'), 366, 1)
    with pytest.raises(IndexError):
        p.value(ts, si) 
Example #3
Source File: test_period.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_min_max(self):
        arr = period_array([
            '2000-01-03',
            '2000-01-03',
            'NaT',
            '2000-01-02',
            '2000-01-05',
            '2000-01-04',
        ], freq='D')

        result = arr.min()
        expected = pd.Period('2000-01-02', freq='D')
        assert result == expected

        result = arr.max()
        expected = pd.Period('2000-01-05', freq='D')
        assert result == expected

        result = arr.min(skipna=False)
        assert result is pd.NaT

        result = arr.max(skipna=False)
        assert result is pd.NaT 
Example #4
Source File: test_datetimelike.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_take_fill_valid(self, datetime_index, tz_naive_fixture):
        dti = datetime_index.tz_localize(tz_naive_fixture)
        arr = DatetimeArray(dti)

        now = pd.Timestamp.now().tz_localize(dti.tz)
        result = arr.take([-1, 1], allow_fill=True, fill_value=now)
        assert result[0] == now

        with pytest.raises(ValueError):
            # fill_value Timedelta invalid
            arr.take([-1, 1], allow_fill=True, fill_value=now - now)

        with pytest.raises(ValueError):
            # fill_value Period invalid
            arr.take([-1, 1], allow_fill=True, fill_value=pd.Period('2014Q1'))

        tz = None if dti.tz is not None else 'US/Eastern'
        now = pd.Timestamp.now().tz_localize(tz)
        with pytest.raises(TypeError):
            # Timestamp with mismatched tz-awareness
            arr.take([-1, 1], allow_fill=True, fill_value=now)

        with pytest.raises(ValueError):
            # require NaT, not iNaT, as it could be confused with an integer
            arr.take([-1, 1], allow_fill=True, fill_value=pd.NaT.value) 
Example #5
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_is_monotonic_increasing(self):
        # GH 17717
        p0 = pd.Period('2017-09-01')
        p1 = pd.Period('2017-09-02')
        p2 = pd.Period('2017-09-03')

        idx_inc0 = pd.PeriodIndex([p0, p1, p2])
        idx_inc1 = pd.PeriodIndex([p0, p1, p1])
        idx_dec0 = pd.PeriodIndex([p2, p1, p0])
        idx_dec1 = pd.PeriodIndex([p2, p1, p1])
        idx = pd.PeriodIndex([p1, p2, p0])

        assert idx_inc0.is_monotonic_increasing is True
        assert idx_inc1.is_monotonic_increasing is True
        assert idx_dec0.is_monotonic_increasing is False
        assert idx_dec1.is_monotonic_increasing is False
        assert idx.is_monotonic_increasing is False 
Example #6
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_is_monotonic_decreasing(self):
        # GH 17717
        p0 = pd.Period('2017-09-01')
        p1 = pd.Period('2017-09-02')
        p2 = pd.Period('2017-09-03')

        idx_inc0 = pd.PeriodIndex([p0, p1, p2])
        idx_inc1 = pd.PeriodIndex([p0, p1, p1])
        idx_dec0 = pd.PeriodIndex([p2, p1, p0])
        idx_dec1 = pd.PeriodIndex([p2, p1, p1])
        idx = pd.PeriodIndex([p1, p2, p0])

        assert idx_inc0.is_monotonic_decreasing is False
        assert idx_inc1.is_monotonic_decreasing is False
        assert idx_dec0.is_monotonic_decreasing is True
        assert idx_dec1.is_monotonic_decreasing is True
        assert idx.is_monotonic_decreasing is False 
Example #7
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_get_indexer_non_unique(self):
        # GH 17717
        p1 = pd.Period('2017-09-02')
        p2 = pd.Period('2017-09-03')
        p3 = pd.Period('2017-09-04')
        p4 = pd.Period('2017-09-05')

        idx1 = pd.PeriodIndex([p1, p2, p1])
        idx2 = pd.PeriodIndex([p2, p1, p3, p4])

        result = idx1.get_indexer_non_unique(idx2)
        expected_indexer = np.array([1, 0, 2, -1, -1], dtype=np.intp)
        expected_missing = np.array([2, 3], dtype=np.int64)

        tm.assert_numpy_array_equal(result[0], expected_indexer)
        tm.assert_numpy_array_equal(result[1], expected_missing)

    # TODO: This method came from test_period; de-dup with version above 
Example #8
Source File: test_construction.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_construction_base_constructor(self):
        # GH 13664
        arr = [pd.Period('2011-01', freq='M'), pd.NaT,
               pd.Period('2011-03', freq='M')]
        tm.assert_index_equal(pd.Index(arr), pd.PeriodIndex(arr))
        tm.assert_index_equal(pd.Index(np.array(arr)),
                              pd.PeriodIndex(np.array(arr)))

        arr = [np.nan, pd.NaT, pd.Period('2011-03', freq='M')]
        tm.assert_index_equal(pd.Index(arr), pd.PeriodIndex(arr))
        tm.assert_index_equal(pd.Index(np.array(arr)),
                              pd.PeriodIndex(np.array(arr)))

        arr = [pd.Period('2011-01', freq='M'), pd.NaT,
               pd.Period('2011-03', freq='D')]
        tm.assert_index_equal(pd.Index(arr), pd.Index(arr, dtype=object))

        tm.assert_index_equal(pd.Index(np.array(arr)),
                              pd.Index(np.array(arr), dtype=object)) 
Example #9
Source File: test_construction.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_constructor_incompat_freq(self):
        msg = "Input has different freq=D from PeriodIndex\\(freq=M\\)"

        with pytest.raises(period.IncompatibleFrequency, match=msg):
            PeriodIndex([Period('2011-01', freq='M'), pd.NaT,
                         Period('2011-01', freq='D')])

        with pytest.raises(period.IncompatibleFrequency, match=msg):
            PeriodIndex(np.array([Period('2011-01', freq='M'), pd.NaT,
                                  Period('2011-01', freq='D')]))

        # first element is pd.NaT
        with pytest.raises(period.IncompatibleFrequency, match=msg):
            PeriodIndex([pd.NaT, Period('2011-01', freq='M'),
                         Period('2011-01', freq='D')])

        with pytest.raises(period.IncompatibleFrequency, match=msg):
            PeriodIndex(np.array([pd.NaT, Period('2011-01', freq='M'),
                                  Period('2011-01', freq='D')])) 
Example #10
Source File: test_tools.py    From recruit with Apache License 2.0 6 votes vote down vote up
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)
            assert period.year == 1969

        period = Period(ordinal=-1, freq='B')
        repr(period)
        period = Period(ordinal=-1, freq='W')
        repr(period) 
Example #11
Source File: test_tools.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_to_period(self):
        dti = pd.date_range(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')

        assert pi1[0] == Period('Jan 2005', freq='M')
        assert pi2[0] == Period('1/31/2005', freq='D')
        assert pi3[0] == Period('1/31/2005', freq='3D')

        assert pi1[-1] == Period('Nov 2005', freq='M')
        assert pi2[-1] == Period('11/30/2005', freq='D')
        assert 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')) 
Example #12
Source File: test_tools.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_searchsorted(self, freq):
        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)
        assert pidx.searchsorted(p1) == 0

        p2 = pd.Period('2014-01-04', freq=freq)
        assert pidx.searchsorted(p2) == 3

        msg = "Input has different freq=H from PeriodIndex"
        with pytest.raises(period.IncompatibleFrequency, match=msg):
            pidx.searchsorted(pd.Period('2014-01-01', freq='H'))

        msg = "Input has different freq=5D from PeriodIndex"
        with pytest.raises(period.IncompatibleFrequency, match=msg):
            pidx.searchsorted(pd.Period('2014-01-01', freq='5D')) 
Example #13
Source File: test_partial_slicing.py    From recruit with Apache License 2.0 6 votes vote down vote up
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):
            tm.assert_series_equal(ts[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[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]) 
Example #14
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_astype_conversion(self):
        # GH#13149, GH#13209
        idx = PeriodIndex(['2016-05-16', 'NaT', NaT, np.NaN], freq='D')

        result = idx.astype(object)
        expected = Index([Period('2016-05-16', freq='D')] +
                         [Period(NaT, freq='D')] * 3, dtype='object')
        tm.assert_index_equal(result, expected)

        result = idx.astype(np.int64)
        expected = Int64Index([16937] + [-9223372036854775808] * 3,
                              dtype=np.int64)
        tm.assert_index_equal(result, expected)

        result = idx.astype(str)
        expected = Index(str(x) for x in idx)
        tm.assert_index_equal(result, expected)

        idx = period_range('1990', '2009', freq='A')
        result = idx.astype('i8')
        tm.assert_index_equal(result, Index(idx.asi8))
        tm.assert_numpy_array_equal(result.values, idx.asi8) 
Example #15
Source File: test_constructors.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_constructor_cant_cast_datetimelike(self, index):

        # floats are not ok
        msg = "Cannot cast {}.*? to ".format(
            # strip Index to convert PeriodIndex -> Period
            # We don't care whether the error message says
            # PeriodIndex or PeriodArray
            type(index).__name__.rstrip("Index")
        )
        with pytest.raises(TypeError, match=msg):
            Series(index, dtype=float)

        # ints are ok
        # we test with np.int64 to get similar results on
        # windows / 32-bit platforms
        result = Series(index, dtype=np.int64)
        expected = Series(index.astype(np.int64))
        tm.assert_series_equal(result, expected) 
Example #16
Source File: test_analytics.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_value_counts_period(self):
        values = [pd.Period('2011-01', freq='M'),
                  pd.Period('2011-02', freq='M'),
                  pd.Period('2011-03', freq='M'),
                  pd.Period('2011-01', freq='M'),
                  pd.Period('2011-01', freq='M'),
                  pd.Period('2011-03', freq='M')]

        exp_idx = pd.PeriodIndex(['2011-01', '2011-03', '2011-02'], freq='M')
        exp = pd.Series([3, 2, 1], index=exp_idx, name='xxx')

        s = pd.Series(values, name='xxx')
        tm.assert_series_equal(s.value_counts(), exp)
        # check DatetimeIndex outputs the same result
        idx = pd.PeriodIndex(values, name='xxx')
        tm.assert_series_equal(idx.value_counts(), exp)

        # normalize
        exp = pd.Series(np.array([3., 2., 1]) / 6.,
                        index=exp_idx, name='xxx')
        tm.assert_series_equal(s.value_counts(normalize=True), exp)
        tm.assert_series_equal(idx.value_counts(normalize=True), exp) 
Example #17
Source File: test_coercion.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_insert_index_period(self, insert, coerced_val, coerced_dtype):
        obj = pd.PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'],
                             freq='M')
        assert obj.dtype == 'period[M]'

        if isinstance(insert, pd.Period):
            index_type = pd.PeriodIndex
        else:
            index_type = pd.Index

        exp = index_type([pd.Period('2011-01', freq='M'),
                          coerced_val,
                          pd.Period('2011-02', freq='M'),
                          pd.Period('2011-03', freq='M'),
                          pd.Period('2011-04', freq='M')], freq='M')
        self._assert_insert_conversion(obj, insert, exp, coerced_dtype) 
Example #18
Source File: test_concat.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _check_expected_dtype(self, obj, label):
        """
        Check whether obj has expected dtype depending on label
        considering not-supported dtypes
        """
        if isinstance(obj, pd.Index):
            if label == 'bool':
                assert obj.dtype == 'object'
            else:
                assert obj.dtype == label
        elif isinstance(obj, pd.Series):
            if label.startswith('period'):
                assert obj.dtype == 'Period[M]'
            else:
                assert obj.dtype == label
        else:
            raise ValueError 
Example #19
Source File: test_multilevel.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_reset_index_period(self):
        # GH 7746
        idx = MultiIndex.from_product(
            [pd.period_range('20130101', periods=3, freq='M'), list('abc')],
            names=['month', 'feature'])

        df = DataFrame(np.arange(9, dtype='int64').reshape(-1, 1),
                       index=idx, columns=['a'])
        expected = 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'])
        tm.assert_frame_equal(df.reset_index(), expected) 
Example #20
Source File: test_period.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_values(self):
        idx = pd.PeriodIndex([], freq='M')

        exp = np.array([], dtype=np.object)
        tm.assert_numpy_array_equal(idx.values, exp)
        tm.assert_numpy_array_equal(idx.get_values(), exp)
        exp = np.array([], dtype=np.int64)
        tm.assert_numpy_array_equal(idx._ndarray_values, exp)

        idx = pd.PeriodIndex(['2011-01', pd.NaT], freq='M')

        exp = np.array([pd.Period('2011-01', freq='M'), pd.NaT], dtype=object)
        tm.assert_numpy_array_equal(idx.values, exp)
        tm.assert_numpy_array_equal(idx.get_values(), exp)
        exp = np.array([492, -9223372036854775808], dtype=np.int64)
        tm.assert_numpy_array_equal(idx._ndarray_values, exp)

        idx = pd.PeriodIndex(['2011-01-01', pd.NaT], freq='D')

        exp = np.array([pd.Period('2011-01-01', freq='D'), pd.NaT],
                       dtype=object)
        tm.assert_numpy_array_equal(idx.values, exp)
        tm.assert_numpy_array_equal(idx.get_values(), exp)
        exp = np.array([14975, -9223372036854775808], dtype=np.int64)
        tm.assert_numpy_array_equal(idx._ndarray_values, exp) 
Example #21
Source File: test_period.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_difference_freq(self, sort):
        # GH14323: difference of Period MUST preserve frequency
        # but the ability to union results must be preserved

        index = period_range("20160920", "20160925", freq="D")

        other = period_range("20160921", "20160924", freq="D")
        expected = PeriodIndex(["20160920", "20160925"], freq='D')
        idx_diff = index.difference(other, sort)
        tm.assert_index_equal(idx_diff, expected)
        tm.assert_attr_equal('freq', idx_diff, expected)

        other = period_range("20160922", "20160925", freq="D")
        idx_diff = index.difference(other, sort)
        expected = PeriodIndex(["20160920", "20160921"], freq='D')
        tm.assert_index_equal(idx_diff, expected)
        tm.assert_attr_equal('freq', idx_diff, expected) 
Example #22
Source File: test_period.py    From recruit with Apache License 2.0 6 votes vote down vote up
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')
        tm.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)
        tm.assert_index_equal(idx.fillna('x'), exp)

        exp = pd.Index([pd.Period('2011-01-01 09:00', freq='H'),
                        pd.Period('2011-01-01', freq='D'),
                        pd.Period('2011-01-01 11:00', freq='H')], dtype=object)
        tm.assert_index_equal(idx.fillna(
            pd.Period('2011-01-01', freq='D')), exp) 
Example #23
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_astype_object(self):
        idx = pd.PeriodIndex([], freq='M')

        exp = np.array([], dtype=object)
        tm.assert_numpy_array_equal(idx.astype(object).values, exp)
        tm.assert_numpy_array_equal(idx._mpl_repr(), exp)

        idx = pd.PeriodIndex(['2011-01', pd.NaT], freq='M')

        exp = np.array([pd.Period('2011-01', freq='M'), pd.NaT], dtype=object)
        tm.assert_numpy_array_equal(idx.astype(object).values, exp)
        tm.assert_numpy_array_equal(idx._mpl_repr(), exp)

        exp = np.array([pd.Period('2011-01-01', freq='D'), pd.NaT],
                       dtype=object)
        idx = pd.PeriodIndex(['2011-01-01', pd.NaT], freq='D')
        tm.assert_numpy_array_equal(idx.astype(object).values, exp)
        tm.assert_numpy_array_equal(idx._mpl_repr(), exp)

    # TODO: de-duplicate this version (from test_ops) with the one above
    # (from test_period) 
Example #24
Source File: test_pivot.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_pivot_periods(self, method):
        df = DataFrame({'p1': [pd.Period('2013-01-01', 'D'),
                               pd.Period('2013-01-02', 'D'),
                               pd.Period('2013-01-01', 'D'),
                               pd.Period('2013-01-02', 'D')],
                        'p2': [pd.Period('2013-01', 'M'),
                               pd.Period('2013-01', 'M'),
                               pd.Period('2013-02', 'M'),
                               pd.Period('2013-02', 'M')],
                        'data1': np.arange(4, dtype='int64'),
                        'data2': np.arange(4, dtype='int64')})

        exp_col1 = Index(['data1', 'data1', 'data2', 'data2'])
        exp_col2 = pd.PeriodIndex(['2013-01', '2013-02'] * 2,
                                  name='p2', freq='M')
        exp_col = pd.MultiIndex.from_arrays([exp_col1, exp_col2])
        expected = DataFrame([[0, 2, 0, 2], [1, 3, 1, 3]],
                             index=pd.PeriodIndex(['2013-01-01', '2013-01-02'],
                                                  name='p1', freq='D'),
                             columns=exp_col)
        if method:
            pv = df.pivot(index='p1', columns='p2')
        else:
            pv = pd.pivot(df, index='p1', columns='p2')
        tm.assert_frame_equal(pv, expected)

        expected = DataFrame([[0, 2], [1, 3]],
                             index=pd.PeriodIndex(['2013-01-01', '2013-01-02'],
                                                  name='p1', freq='D'),
                             columns=pd.PeriodIndex(['2013-01', '2013-02'],
                                                    name='p2', freq='M'))
        if method:
            pv = df.pivot(index='p1', columns='p2', values='data1')
        else:
            pv = pd.pivot(df, index='p1', columns='p2', values='data1')
        tm.assert_frame_equal(pv, expected) 
Example #25
Source File: test_datetime.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_series_partial_set_period(self):
        # GH 11497

        idx = pd.period_range('2011-01-01', '2011-01-02', freq='D', name='idx')
        ser = Series([0.1, 0.2], index=idx, name='s')

        result = ser.loc[[pd.Period('2011-01-01', freq='D'),
                          pd.Period('2011-01-02', freq='D')]]
        exp = Series([0.1, 0.2], index=idx, name='s')
        tm.assert_series_equal(result, exp, check_index_type=True)

        keys = [pd.Period('2011-01-02', freq='D'),
                pd.Period('2011-01-02', freq='D'),
                pd.Period('2011-01-01', freq='D')]
        exp = Series([0.2, 0.2, 0.1], index=pd.PeriodIndex(keys, name='idx'),
                     name='s')
        tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True)

        keys = [pd.Period('2011-01-03', freq='D'),
                pd.Period('2011-01-02', freq='D'),
                pd.Period('2011-01-03', freq='D')]
        exp = Series([np.nan, 0.2, np.nan],
                     index=pd.PeriodIndex(keys, name='idx'), name='s')
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            result = ser.loc[keys]
        tm.assert_series_equal(result, exp) 
Example #26
Source File: test_license.py    From pywr with GNU General Public License v3.0 5 votes vote down vote up
def test_daily_license(simple_linear_model):
    '''Test daily licence'''
    m = simple_linear_model
    si = ScenarioIndex(0, np.array([0], dtype=np.int32))
    lic = TimestepLicense(m, None, 42.0)
    assert(isinstance(lic, License))
    assert(lic.value(Timestep(pandas.Period('2015-1-1'), 0, 1), si) == 42.0)

    # daily licences don't have resource state
    assert(lic.resource_state(Timestep(pandas.Period('2015-1-1'), 0, 1)) is None) 
Example #27
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_iter_box(self):
        vals = [Timestamp('2011-01-01'), Timestamp('2011-01-02')]
        s = Series(vals)
        assert s.dtype == 'datetime64[ns]'
        for res, exp in zip(s, vals):
            assert isinstance(res, Timestamp)
            assert res.tz is None
            assert res == exp

        vals = [Timestamp('2011-01-01', tz='US/Eastern'),
                Timestamp('2011-01-02', tz='US/Eastern')]
        s = Series(vals)

        assert s.dtype == 'datetime64[ns, US/Eastern]'
        for res, exp in zip(s, vals):
            assert isinstance(res, Timestamp)
            assert res.tz == exp.tz
            assert res == exp

        # timedelta
        vals = [Timedelta('1 days'), Timedelta('2 days')]
        s = Series(vals)
        assert s.dtype == 'timedelta64[ns]'
        for res, exp in zip(s, vals):
            assert isinstance(res, Timedelta)
            assert res == exp

        # period
        vals = [pd.Period('2011-01-01', freq='M'),
                pd.Period('2011-01-02', freq='M')]
        s = Series(vals)
        assert s.dtype == 'Period[M]'
        for res, exp in zip(s, vals):
            assert isinstance(res, pd.Period)
            assert res.freq == 'M'
            assert res == exp 
Example #28
Source File: test_frame.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_subplots_timeseries_y_axis_not_supported(self):
        """
        This test will fail for:
            period:
                since period isn't yet implemented in ``select_dtypes``
                and because it will need a custom value converter +
                tick formater (as was done for x-axis plots)

            categorical:
                 because it will need a custom value converter +
                 tick formater (also doesn't work for x-axis, as of now)

            datetime_mixed_tz:
                because of the way how pandas handels ``Series`` of
                ``datetime`` objects with different timezone,
                generally converting ``datetime`` objects in a tz-aware
                form could help with this problem
        """
        data = {"numeric": np.array([1, 2, 5]),
                "period": [pd.Period('2017-08-01 00:00:00', freq='H'),
                           pd.Period('2017-08-01 02:00', freq='H'),
                           pd.Period('2017-08-02 00:00:00', freq='H')],
                "categorical": pd.Categorical(["c", "b", "a"],
                                              categories=["a", "b", "c"],
                                              ordered=False),
                "datetime_mixed_tz": [pd.to_datetime("2017-08-01 00:00:00",
                                                     utc=True),
                                      pd.to_datetime("2017-08-01 02:00:00"),
                                      pd.to_datetime("2017-08-02 00:00:00")]}
        testdata = pd.DataFrame(data)
        ax_period = testdata.plot(x="numeric", y="period")
        assert (ax_period.get_lines()[0].get_data()[1] ==
                testdata["period"].values).all()
        ax_categorical = testdata.plot(x="numeric", y="categorical")
        assert (ax_categorical.get_lines()[0].get_data()[1] ==
                testdata["categorical"].values).all()
        ax_datetime_mixed_tz = testdata.plot(x="numeric",
                                             y="datetime_mixed_tz")
        assert (ax_datetime_mixed_tz.get_lines()[0].get_data()[1] ==
                testdata["datetime_mixed_tz"].values).all() 
Example #29
Source File: test_period.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_with_multi_index(self):
        # #1705
        index = date_range('1/1/2012', periods=4, freq='12H')
        index_as_arrays = [index.to_period(freq='D'), index.hour]

        s = Series([0, 1, 2, 3], index_as_arrays)

        assert isinstance(s.index.levels[0], PeriodIndex)

        assert isinstance(s.index.values[0][0], Period) 
Example #30
Source File: test_period.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_registered():
    assert PeriodDtype in registry.dtypes
    result = registry.find("Period[D]")
    expected = PeriodDtype("D")
    assert result == expected

# ----------------------------------------------------------------------------
# period_array