Example #1
0
 def _maybe_convert_timedelta(self, other):
     if isinstance(other,
                   (timedelta, np.timedelta64, offsets.Tick, Timedelta)):
         offset = frequencies.to_offset(self.freq.rule_code)
         if isinstance(offset, offsets.Tick):
             nanos = tslib._delta_to_nanoseconds(other)
             offset_nanos = tslib._delta_to_nanoseconds(offset)
             if nanos % offset_nanos == 0:
                 return nanos // offset_nanos
     elif isinstance(other, offsets.DateOffset):
         freqstr = frequencies.get_standard_freq(other)
         base = frequencies.get_base_alias(freqstr)
         if base == self.freq.rule_code:
             return other.n
     elif isinstance(other, np.ndarray):
         if com.is_integer_dtype(other):
             return other
         elif com.is_timedelta64_dtype(other):
             offset = frequencies.to_offset(self.freq)
             if isinstance(offset, offsets.Tick):
                 nanos = tslib._delta_to_nanoseconds(other)
                 offset_nanos = tslib._delta_to_nanoseconds(offset)
                 if (nanos % offset_nanos).all() == 0:
                     return nanos // offset_nanos
     msg = "Input has different freq from PeriodIndex(freq={0})"
     raise ValueError(msg.format(self.freqstr))
Example #2
0
    def __new__(cls, data=None, ordinal=None,
                freq=None, start=None, end=None, periods=None,
                copy=False, name=None,
                year=None, month=None, quarter=None, day=None,
                hour=None, minute=None, second=None):

        freq = _freq_mod.get_standard_freq(freq)

        if periods is not None:
            if com.is_float(periods):
                periods = int(periods)
            elif not com.is_integer(periods):
                raise ValueError('Periods must be a number, got %s' %
                                 str(periods))

        if data is None:
            if ordinal is not None:
                data = np.asarray(ordinal, dtype=np.int64)
            else:
                fields = [year, month, quarter, day, hour, minute, second]
                data, freq = cls._generate_range(start, end, periods,
                                                    freq, fields)
        else:
            ordinal, freq = cls._from_arraylike(data, freq)
            data = np.array(ordinal, dtype=np.int64, copy=False)

        subarr = data.view(cls)
        subarr.name = name
        subarr.freq = freq

        return subarr
Example #3
0
 def _maybe_convert_timedelta(self, other):
     if isinstance(other,
                   (timedelta, np.timedelta64, offsets.Tick, Timedelta)):
         offset = frequencies.to_offset(self.freq.rule_code)
         if isinstance(offset, offsets.Tick):
             nanos = tslib._delta_to_nanoseconds(other)
             offset_nanos = tslib._delta_to_nanoseconds(offset)
             if nanos % offset_nanos == 0:
                 return nanos // offset_nanos
     elif isinstance(other, offsets.DateOffset):
         freqstr = frequencies.get_standard_freq(other)
         base = frequencies.get_base_alias(freqstr)
         if base == self.freq.rule_code:
             return other.n
         msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr)
         raise IncompatibleFrequency(msg)
     elif isinstance(other, np.ndarray):
         if com.is_integer_dtype(other):
             return other
         elif com.is_timedelta64_dtype(other):
             offset = frequencies.to_offset(self.freq)
             if isinstance(offset, offsets.Tick):
                 nanos = tslib._delta_to_nanoseconds(other)
                 offset_nanos = tslib._delta_to_nanoseconds(offset)
                 if (nanos % offset_nanos).all() == 0:
                     return nanos // offset_nanos
     # raise when input doesn't have freq
     msg = "Input has different freq from PeriodIndex(freq={0})"
     raise IncompatibleFrequency(msg.format(self.freqstr))
Example #4
0
    def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None,
                periods=None, copy=False, name=None, year=None, month=None,
                quarter=None, day=None, hour=None, minute=None, second=None,
                tz=None):

        freq = _freq_mod.get_standard_freq(freq)

        if periods is not None:
            if com.is_float(periods):
                periods = int(periods)
            elif not com.is_integer(periods):
                raise ValueError('Periods must be a number, got %s' %
                                 str(periods))

        if data is None:
            if ordinal is not None:
                data = np.asarray(ordinal, dtype=np.int64)
            else:
                fields = [year, month, quarter, day, hour, minute, second]
                data, freq = cls._generate_range(start, end, periods,
                                                 freq, fields)
        else:
            ordinal, freq = cls._from_arraylike(data, freq, tz)
            data = np.array(ordinal, dtype=np.int64, copy=False)

        subarr = data.view(cls)
        subarr.name = name
        subarr.freq = freq

        return subarr
Example #5
0
File: period.py Project: DT021/wau
    def __new__(cls,
                data=None,
                ordinal=None,
                freq=None,
                start=None,
                end=None,
                periods=None,
                copy=False,
                name=None,
                tz=None,
                **kwargs):

        freq = frequencies.get_standard_freq(freq)

        if periods is not None:
            if is_float(periods):
                periods = int(periods)
            elif not is_integer(periods):
                raise ValueError('Periods must be a number, got %s' %
                                 str(periods))

        if data is None:
            if ordinal is not None:
                data = np.asarray(ordinal, dtype=np.int64)
            else:
                data, freq = cls._generate_range(start, end, periods, freq,
                                                 kwargs)
        else:
            ordinal, freq = cls._from_arraylike(data, freq, tz)
            data = np.array(ordinal, dtype=np.int64, copy=False)

        return cls._simple_new(data, name=name, freq=freq)
Example #6
0
    def test_frequency_misc(self):
        assert (resolution.get_freq_group('T') ==
                frequencies.FreqGroup.FR_MIN)

        code, stride = frequencies.get_freq_code(offsets.Hour())
        assert code == frequencies.FreqGroup.FR_HR

        code, stride = frequencies.get_freq_code((5, 'T'))
        assert code == frequencies.FreqGroup.FR_MIN
        assert stride == 5

        offset = offsets.Hour()
        result = frequencies.to_offset(offset)
        assert result == offset

        result = frequencies.to_offset((5, 'T'))
        expected = offsets.Minute(5)
        assert result == expected

        with tm.assert_raises_regex(ValueError, 'Invalid frequency'):
            frequencies.get_freq_code((5, 'baz'))

        with tm.assert_raises_regex(ValueError, 'Invalid frequency'):
            frequencies.to_offset('100foo')

        with tm.assert_raises_regex(ValueError, 'Could not evaluate'):
            frequencies.to_offset(('', ''))

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            result = frequencies.get_standard_freq(offsets.Hour())
        assert result == 'H'
Example #7
0
 def _maybe_convert_timedelta(self, other):
     if isinstance(other, (timedelta, np.timedelta64, offsets.Tick, Timedelta)):
         offset = frequencies.to_offset(self.freq.rule_code)
         if isinstance(offset, offsets.Tick):
             nanos = tslib._delta_to_nanoseconds(other)
             offset_nanos = tslib._delta_to_nanoseconds(offset)
             if nanos % offset_nanos == 0:
                 return nanos // offset_nanos
     elif isinstance(other, offsets.DateOffset):
         freqstr = frequencies.get_standard_freq(other)
         base = frequencies.get_base_alias(freqstr)
         if base == self.freq.rule_code:
             return other.n
     elif isinstance(other, np.ndarray):
         if com.is_integer_dtype(other):
             return other
         elif com.is_timedelta64_dtype(other):
             offset = frequencies.to_offset(self.freq)
             if isinstance(offset, offsets.Tick):
                 nanos = tslib._delta_to_nanoseconds(other)
                 offset_nanos = tslib._delta_to_nanoseconds(offset)
                 if (nanos % offset_nanos).all() == 0:
                     return nanos // offset_nanos
     msg = "Input has different freq from PeriodIndex(freq={0})"
     raise ValueError(msg.format(self.freqstr))
Example #8
0
    def __new__(cls, data=None, ordinal=None,
                freq=None, start=None, end=None, periods=None,
                copy=False, name=None,
                year=None, month=None, quarter=None, day=None,
                hour=None, minute=None, second=None):

        if isinstance(freq, Period):
            freq = freq.freq
        else:
            freq = _freq_mod.get_standard_freq(freq)

        if data is None:
            if ordinal is not None:
                data = np.asarray(ordinal, dtype=np.int64)
            else:
                fields = [year, month, quarter, day, hour, minute, second]
                data, freq = cls._generate_range(start, end, periods,
                                                    freq, fields)
        else:
            ordinal, freq = cls._from_arraylike(data, freq)
            data = np.array(ordinal, dtype=np.int64, copy=False)

        subarr = data.view(cls)
        subarr.name = name
        subarr.freq = freq

        return subarr
Example #9
0
    def asfreq(self, freq=None, how='E'):
        how = _validate_end_alias(how)

        freq = _freq_mod.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)

        if isinstance(freq, basestring):
            base2, mult2 = _gfc(freq)
        else:
            base2, mult2 = freq

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        if how not in ('S', 'E'):
            raise ValueError('relation argument must be one of S or E')

        end = how == 'E'
        new_data = lib.period_asfreq_arr(self.values, base1, base2, end)

        result = new_data.view(PeriodIndex)
        result.name = self.name
        result.freq = freq
        return result
Example #10
0
    def test_frequency_misc(self):
        assert (resolution.get_freq_group('T') == frequencies.FreqGroup.FR_MIN)

        code, stride = frequencies.get_freq_code(offsets.Hour())
        assert code == frequencies.FreqGroup.FR_HR

        code, stride = frequencies.get_freq_code((5, 'T'))
        assert code == frequencies.FreqGroup.FR_MIN
        assert stride == 5

        offset = offsets.Hour()
        result = frequencies.to_offset(offset)
        assert result == offset

        result = frequencies.to_offset((5, 'T'))
        expected = offsets.Minute(5)
        assert result == expected

        with tm.assert_raises_regex(ValueError, 'Invalid frequency'):
            frequencies.get_freq_code((5, 'baz'))

        with tm.assert_raises_regex(ValueError, 'Invalid frequency'):
            frequencies.to_offset('100foo')

        with tm.assert_raises_regex(ValueError, 'Could not evaluate'):
            frequencies.to_offset(('', ''))

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            result = frequencies.get_standard_freq(offsets.Hour())
        assert result == 'H'
Example #11
0
    def asfreq(self, freq=None, how='E'):
        how = _validate_end_alias(how)

        freq = _freq_mod.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)

        if isinstance(freq, basestring):
            base2, mult2 = _gfc(freq)
        else:
            base2, mult2 = freq

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        if how not in ('S', 'E'):
            raise ValueError('relation argument must be one of S or E')

        end = how == 'E'
        new_data = plib.period_asfreq_arr(self.values, base1, base2, end)

        result = new_data.view(PeriodIndex)
        result.name = self.name
        result.freq = freq
        return result
Example #12
0
    def __new__(
        cls,
        data=None,
        ordinal=None,
        freq=None,
        start=None,
        end=None,
        periods=None,
        copy=False,
        name=None,
        tz=None,
        **kwargs
    ):

        freq = frequencies.get_standard_freq(freq)

        if periods is not None:
            if com.is_float(periods):
                periods = int(periods)
            elif not com.is_integer(periods):
                raise ValueError("Periods must be a number, got %s" % str(periods))

        if data is None:
            if ordinal is not None:
                data = np.asarray(ordinal, dtype=np.int64)
            else:
                data, freq = cls._generate_range(start, end, periods, freq, kwargs)
        else:
            ordinal, freq = cls._from_arraylike(data, freq, tz)
            data = np.array(ordinal, dtype=np.int64, copy=False)

        return cls._simple_new(data, name=name, freq=freq)
Example #13
0
 def _maybe_convert_timedelta(self, other):
     if isinstance(other, (timedelta, np.timedelta64,
                           offsets.Tick, Timedelta)):
         offset = frequencies.to_offset(self.freq.rule_code)
         if isinstance(offset, offsets.Tick):
             nanos = tslib._delta_to_nanoseconds(other)
             offset_nanos = tslib._delta_to_nanoseconds(offset)
             if nanos % offset_nanos == 0:
                 return nanos // offset_nanos
     elif isinstance(other, offsets.DateOffset):
         freqstr = frequencies.get_standard_freq(other)
         base = frequencies.get_base_alias(freqstr)
         if base == self.freq.rule_code:
             return other.n
         msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr)
         raise IncompatibleFrequency(msg)
     elif isinstance(other, np.ndarray):
         if com.is_integer_dtype(other):
             return other
         elif com.is_timedelta64_dtype(other):
             offset = frequencies.to_offset(self.freq)
             if isinstance(offset, offsets.Tick):
                 nanos = tslib._delta_to_nanoseconds(other)
                 offset_nanos = tslib._delta_to_nanoseconds(offset)
                 if (nanos % offset_nanos).all() == 0:
                     return nanos // offset_nanos
     # raise when input doesn't have freq
     msg = "Input has different freq from PeriodIndex(freq={0})"
     raise IncompatibleFrequency(msg.format(self.freqstr))
Example #14
0
    def test_frequency_misc(self):
        self.assertEquals(fmod.get_freq_group('T'),
                          fmod.FreqGroup.FR_MIN)

        code, stride = fmod.get_freq_code(offsets.Hour())
        self.assertEquals(code, fmod.FreqGroup.FR_HR)

        code, stride = fmod.get_freq_code((5, 'T'))
        self.assertEquals(code, fmod.FreqGroup.FR_MIN)
        self.assertEquals(stride, 5)

        offset = offsets.Hour()
        result = fmod.to_offset(offset)
        self.assertEquals(result, offset)

        result = fmod.to_offset((5, 'T'))
        expected = offsets.Minute(5)
        self.assertEquals(result, expected)

        self.assertRaises(KeyError, fmod.get_freq_code, (5, 'baz'))

        self.assertRaises(ValueError, fmod.to_offset, '100foo')

        self.assertRaises(ValueError, fmod.to_offset, ('', ''))

        result = fmod.get_standard_freq(offsets.Hour())
        self.assertEquals(result, 'H')
Example #15
0
File: period.py Project: DT021/wau
    def asfreq(self, freq=None, how='E'):
        """
        Convert the PeriodIndex to the specified frequency `freq`.

        Parameters
        ----------

        freq : str
            a frequency
        how : str {'E', 'S'}
            'E', 'END', or 'FINISH' for end,
            'S', 'START', or 'BEGIN' for start.
            Whether the elements should be aligned to the end
            or start within pa period. January 31st ('END') vs.
            Janury 1st ('START') for example.

        Returns
        -------

        new : PeriodIndex with the new frequency

        Examples
        --------
        >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
        >>> pidx
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010, ..., 2015]
        Length: 6, Freq: A-DEC

        >>> pidx.asfreq('M')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-12, ..., 2015-12]
        Length: 6, Freq: M

        >>> pidx.asfreq('M', how='S')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-01, ..., 2015-01]
        Length: 6, Freq: M
        """
        how = _validate_end_alias(how)

        freq = frequencies.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        end = how == 'E'
        new_data = period.period_asfreq_arr(self.values, base1, base2, end)
        return self._simple_new(new_data, self.name, freq=freq)
Example #16
0
    def asfreq(self, freq=None, how='E'):
        """
        Convert the PeriodIndex to the specified frequency `freq`.

        Parameters
        ----------

        freq : str
            a frequency
        how : str {'E', 'S'}
            'E', 'END', or 'FINISH' for end,
            'S', 'START', or 'BEGIN' for start.
            Whether the elements should be aligned to the end
            or start within pa period. January 31st ('END') vs.
            Janury 1st ('START') for example.

        Returns
        -------

        new : PeriodIndex with the new frequency

        Examples
        --------
        >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
        >>> pidx
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010, ..., 2015]
        Length: 6, Freq: A-DEC

        >>> pidx.asfreq('M')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-12, ..., 2015-12]
        Length: 6, Freq: M

        >>> pidx.asfreq('M', how='S')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-01, ..., 2015-01]
        Length: 6, Freq: M
        """
        how = _validate_end_alias(how)

        freq = frequencies.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        end = how == 'E'
        new_data = period.period_asfreq_arr(self.values, base1, base2, end)
        return self._simple_new(new_data, self.name, freq=freq)
Example #17
0
    def asfreq(self, freq=None, how='E'):
        how = _validate_end_alias(how)

        freq = _freq_mod.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        end = how == 'E'
        new_data = tslib.period_asfreq_arr(self.values, base1, base2, end)
        return self._simple_new(new_data, self.name, freq=freq)
Example #18
0
    def asfreq(self, freq=None, how='E'):
        how = _validate_end_alias(how)

        freq = frequencies.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        end = how == 'E'
        new_data = period.period_asfreq_arr(self.values, base1, base2, end)
        return self._simple_new(new_data, self.name, freq=freq)
Example #19
0
    def _add_delta(self, other):
        if isinstance(other, (timedelta, np.timedelta64, offsets.Tick, Timedelta)):
            offset = frequencies.to_offset(self.freq)
            if isinstance(offset, offsets.Tick):
                nanos = tslib._delta_to_nanoseconds(other)
                offset_nanos = tslib._delta_to_nanoseconds(offset)
                if nanos % offset_nanos == 0:
                    return self.shift(nanos // offset_nanos)
        elif isinstance(other, offsets.DateOffset):
            freqstr = frequencies.get_standard_freq(other)
            base = frequencies.get_base_alias(freqstr)

            if base == self.freq:
                return self.shift(other.n)
        raise ValueError("Input has different freq from PeriodIndex(freq={0})".format(self.freq))
Example #20
0
    def _add_delta(self, other):
        if isinstance(other, (timedelta, np.timedelta64, offsets.Tick, Timedelta)):
            offset = frequencies.to_offset(self.freq)
            if isinstance(offset, offsets.Tick):
                nanos = tslib._delta_to_nanoseconds(other)
                offset_nanos = tslib._delta_to_nanoseconds(offset)
                if nanos % offset_nanos == 0:
                    return self.shift(nanos // offset_nanos)
        elif isinstance(other, offsets.DateOffset):
            freqstr = frequencies.get_standard_freq(other)
            base = frequencies.get_base_alias(freqstr)

            if base == self.freq:
                return self.shift(other.n)
        raise ValueError("Input has different freq from PeriodIndex(freq={0})".format(self.freq))
Example #21
0
    def asfreq(self, freq=None, how='E'):
        how = _validate_end_alias(how)

        freq = _freq_mod.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        end = how == 'E'
        new_data = plib.period_asfreq_arr(self.values, base1, base2, end)

        result = new_data.view(PeriodIndex)
        result.name = self.name
        result.freq = freq
        return result
Example #22
0
    def asfreq(self, freq=None, how='E'):
        how = _validate_end_alias(how)

        freq = _freq_mod.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        if mult2 != 1:
            raise ValueError('Only mult == 1 supported')

        end = how == 'E'
        new_data = plib.period_asfreq_arr(self.values, base1, base2, end)

        result = new_data.view(PeriodIndex)
        result.name = self.name
        result.freq = freq
        return result
Example #23
0
    def __new__(cls, data=None,
                freq=None, start=None, end=None, periods=None,
                copy=False, name=None):

        if isinstance(freq, Period):
            freq = freq.freq
        else:
            freq = _freq_mod.get_standard_freq(freq)

        if data is None:
            subarr, freq = _get_ordinal_range(start, end, periods, freq)
            subarr = subarr.view(cls)
            subarr.name = name
            subarr.freq = freq

            return subarr

        if not isinstance(data, np.ndarray):
            if np.isscalar(data):
                raise ValueError('PeriodIndex() must be called with a '
                                 'collection of some kind, %s was passed'
                                 % repr(data))

            elif isinstance(data, Period):
                raise ValueError('Data must be array of dates, strings, '
                                 'or Period objects')

            # other iterable of some kind
            if not isinstance(data, (list, tuple)):
                data = list(data)

            try:
                data = np.array(data, dtype='i8')
            except:
                data = np.array(data, dtype='O')

            if freq is None and len(data) > 0:
                freq = getattr(data[0], 'freq', None)

            if freq is None:
                raise ValueError(('freq not specified and cannot be inferred '
                                  'from first element'))

            data = _period_unbox_array(data, check=freq)
        else:
            if isinstance(data, PeriodIndex):
                if freq is None or freq == data.freq:
                    freq = data.freq
                    data = data.values
                else:
                    base1, mult1 = _gfc(data.freq)
                    base2, mult2 = _gfc(freq)
                    how = py3compat.str_to_bytes('E')
                    data = lib.period_asfreq_arr(data.values, base1, mult1,
                                                 base2, mult2, how)
            else:
                if freq is None and len(data) > 0:
                    freq = getattr(data[0], 'freq')

                if freq is None:
                    raise ValueError(('freq not specified and cannot be '
                                      'inferred from first element'))

                if data.dtype == np.datetime64:
                    data = dt64arr_to_periodarr(data, freq)
                elif data.dtype == np.int64:
                    pass
                else:
                    try:
                        data = data.astype('i8')
                    except:
                        data = data.astype('O')
                        data = _period_unbox_array(data, check=freq)

        data = np.array(data, dtype=np.int64, copy=False)

        if (data <= 0).any():
            raise ValueError("Found illegal (<= 0) values in data")

        subarr = data.view(cls)
        subarr.name = name
        subarr.freq = freq

        return subarr
Example #24
0
    def asfreq(self, freq=None, how='E'):
        """
        Convert the PeriodIndex to the specified frequency `freq`.

        Parameters
        ----------

        freq : str
            a frequency
        how : str {'E', 'S'}
            'E', 'END', or 'FINISH' for end,
            'S', 'START', or 'BEGIN' for start.
            Whether the elements should be aligned to the end
            or start within pa period. January 31st ('END') vs.
            Janury 1st ('START') for example.

        Returns
        -------

        new : PeriodIndex with the new frequency

        Examples
        --------
        >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
        >>> pidx
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010, ..., 2015]
        Length: 6, Freq: A-DEC

        >>> pidx.asfreq('M')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-12, ..., 2015-12]
        Length: 6, Freq: M

        >>> pidx.asfreq('M', how='S')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-01, ..., 2015-01]
        Length: 6, Freq: M
        """
        how = _validate_end_alias(how)

        freq = frequencies.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        asi8 = self.asi8
        # mult1 can't be negative or 0
        end = how == 'E'
        if end:
            ordinal = asi8 + mult1 - 1
        else:
            ordinal = asi8

        new_data = period.period_asfreq_arr(ordinal, base1, base2, end)

        if self.hasnans:
            mask = asi8 == tslib.iNaT
            new_data[mask] = tslib.iNaT

        return self._simple_new(new_data, self.name, freq=freq)
Example #25
0
    def asfreq(self, freq=None, how='E'):
        """
        Convert the PeriodIndex to the specified frequency `freq`.

        Parameters
        ----------

        freq : str
            a frequency
        how : str {'E', 'S'}
            'E', 'END', or 'FINISH' for end,
            'S', 'START', or 'BEGIN' for start.
            Whether the elements should be aligned to the end
            or start within pa period. January 31st ('END') vs.
            Janury 1st ('START') for example.

        Returns
        -------

        new : PeriodIndex with the new frequency

        Examples
        --------
        >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
        >>> pidx
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010, ..., 2015]
        Length: 6, Freq: A-DEC

        >>> pidx.asfreq('M')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-12, ..., 2015-12]
        Length: 6, Freq: M

        >>> pidx.asfreq('M', how='S')
        <class 'pandas.tseries.period.PeriodIndex'>
        [2010-01, ..., 2015-01]
        Length: 6, Freq: M
        """
        how = _validate_end_alias(how)

        freq = frequencies.get_standard_freq(freq)

        base1, mult1 = _gfc(self.freq)
        base2, mult2 = _gfc(freq)

        asi8 = self.asi8
        # mult1 can't be negative or 0
        end = how == 'E'
        if end:
            ordinal = asi8 + mult1 - 1
        else:
            ordinal = asi8

        new_data = period.period_asfreq_arr(ordinal, base1, base2, end)

        if self.hasnans:
            mask = asi8 == tslib.iNaT
            new_data[mask] = tslib.iNaT

        return self._simple_new(new_data, self.name, freq=freq)