示例#1
0
def _get_freq(ax, series):
    # get frequency from data
    freq = getattr(series.index, 'freq', None)
    if freq is None:
        freq = getattr(series.index, 'inferred_freq', None)

    ax_freq = getattr(ax, 'freq', None)
    if ax_freq is None:
        if hasattr(ax, 'left_ax'):
            ax_freq = getattr(ax.left_ax, 'freq', None)
        elif hasattr(ax, 'right_ax'):
            ax_freq = getattr(ax.right_ax, 'freq', None)

    # use axes freq if no data freq
    if freq is None:
        freq = ax_freq

    # get the period frequency
    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = frequencies.get_base_alias(freq)

    freq = frequencies.get_period_alias(freq)
    return freq, ax_freq
示例#2
0
def _maybe_convert_index(ax, data):
    # tsplot converts automatically, but don't want to convert index
    # over and over for DataFrames
    if isinstance(data.index, (ABCDatetimeIndex, ABCPeriodIndex)):
        freq = getattr(data.index, "freq", None)

        if freq is None:
            freq = getattr(data.index, "inferred_freq", None)
        if isinstance(freq, DateOffset):
            freq = freq.rule_code

        if freq is None:
            freq = _get_ax_freq(ax)

        if freq is None:
            raise ValueError("Could not get frequency alias for plotting")

        freq = get_base_alias(freq)
        freq = frequencies.get_period_alias(freq)

        if isinstance(data.index, ABCDatetimeIndex):
            data = data.to_period(freq=freq)
        elif isinstance(data.index, ABCPeriodIndex):
            data.index = data.index.asfreq(freq=freq)
    return data
示例#3
0
    def to_period(self, freq=None):
        """
        Cast to PeriodArray/Index at a particular frequency.

        Converts DatetimeArray/Index to PeriodArray/Index.

        Parameters
        ----------
        freq : string or Offset, optional
            One of pandas' :ref:`offset strings <timeseries.offset_aliases>`
            or an Offset object. Will be inferred by default.

        Returns
        -------
        PeriodArray/Index

        Raises
        ------
        ValueError
            When converting a DatetimeArray/Index with non-regular values,
            so that a frequency cannot be inferred.

        Examples
        --------
        >>> df = pd.DataFrame({"y": [1,2,3]},
        ...                   index=pd.to_datetime(["2000-03-31 00:00:00",
        ...                                         "2000-05-31 00:00:00",
        ...                                         "2000-08-31 00:00:00"]))
        >>> df.index.to_period("M")
        PeriodIndex(['2000-03', '2000-05', '2000-08'],
                    dtype='period[M]', freq='M')

        Infer the daily frequency

        >>> idx = pd.date_range("2017-01-01", periods=2)
        >>> idx.to_period()
        PeriodIndex(['2017-01-01', '2017-01-02'],
                    dtype='period[D]', freq='D')

        See also
        --------
        pandas.PeriodIndex: Immutable ndarray holding ordinal values
        pandas.DatetimeIndex.to_pydatetime: Return DatetimeIndex as object
        """
        from pandas.core.arrays import PeriodArrayMixin

        if self.tz is not None:
            warnings.warn("Converting to PeriodArray/Index representation "
                          "will drop timezone information.", UserWarning)

        if freq is None:
            freq = self.freqstr or self.inferred_freq

            if freq is None:
                raise ValueError("You must pass a freq argument as "
                                 "current index has none.")

            freq = get_period_alias(freq)

        return PeriodArrayMixin(self.values, freq=freq)
示例#4
0
文件: plotting.py 项目: r0k3/pandas
    def _maybe_convert_index(self, data):
        # tsplot converts automatically, but don't want to convert index
        # over and over for DataFrames
        from pandas.core.frame import DataFrame
        if (isinstance(data.index, DatetimeIndex) and
            isinstance(data, DataFrame)):
            freq = getattr(data.index, 'freq', None)

            if freq is None:
                freq = getattr(data.index, 'inferred_freq', None)

            if isinstance(freq, DateOffset):
                freq = freq.rule_code

            freq = get_period_alias(freq)

            if freq is None:
                ax = self._get_ax(0)
                freq = getattr(ax, 'freq', None)

            if freq is None:
                raise ValueError('Could not get frequency alias for plotting')

            data = DataFrame(data.values,
                             index=data.index.to_period(freq=freq),
                             columns=data.columns)
        return data
示例#5
0
def _use_dynamic_x(ax, data):
    freq = _get_index_freq(data)
    ax_freq = _get_ax_freq(ax)

    if freq is None:  # convert irregular if axes has freq info
        freq = ax_freq
    else:  # do not use tsplot if irregular was plotted first
        if (ax_freq is None) and (len(ax.get_lines()) > 0):
            return False

    if freq is None:
        return False

    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = frequencies.get_base_alias(freq)
    freq = frequencies.get_period_alias(freq)

    if freq is None:
        return False

    # hack this for 0.10.1, creating more technical debt...sigh
    if isinstance(data.index, ABCDatetimeIndex):
        base = frequencies.get_freq(freq)
        x = data.index
        if (base <= frequencies.FreqGroup.FR_DAY):
            return x[:1].is_normalized
        return Period(x[0], freq).to_timestamp(tz=x.tz) == x[0]
    return True
示例#6
0
文件: plotting.py 项目: r0k3/pandas
 def _is_dynamic_freq(self, freq):
     if isinstance(freq, DateOffset):
         freq = freq.rule_code
     else:
         freq = get_base_alias(freq)
     freq = get_period_alias(freq)
     return freq is not None
示例#7
0
def _get_freq(ax, series):
    # get frequency from data
    freq = getattr(series.index, 'freq', None)
    if freq is None:
        freq = getattr(series.index, 'inferred_freq', None)

    ax_freq = getattr(ax, 'freq', None)
    if ax_freq is None:
        if hasattr(ax, 'left_ax'):
            ax_freq = getattr(ax.left_ax, 'freq', None)
        elif hasattr(ax, 'right_ax'):
            ax_freq = getattr(ax.right_ax, 'freq', None)

    # use axes freq if no data freq
    if freq is None:
        freq = ax_freq

    # get the period frequency
    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = frequencies.get_base_alias(freq)

    freq = frequencies.get_period_alias(freq)
    return freq, ax_freq
示例#8
0
def _use_dynamic_x(ax, data):
    freq = _get_index_freq(data)
    ax_freq = _get_ax_freq(ax)

    if freq is None:  # convert irregular if axes has freq info
        freq = ax_freq
    else:  # do not use tsplot if irregular was plotted first
        if (ax_freq is None) and (len(ax.get_lines()) > 0):
            return False

    if freq is None:
        return False

    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = get_base_alias(freq)
    freq = frequencies.get_period_alias(freq)

    if freq is None:
        return False

    # hack this for 0.10.1, creating more technical debt...sigh
    if isinstance(data.index, ABCDatetimeIndex):
        base = get_freq(freq)
        x = data.index
        if base <= FreqGroup.FR_DAY:
            return x[:1].is_normalized
        return Period(x[0], freq).to_timestamp(tz=x.tz) == x[0]
    return True
示例#9
0
def _maybe_convert_index(ax, data):
    # tsplot converts automatically, but don't want to convert index
    # over and over for DataFrames
    if isinstance(data.index, (ABCDatetimeIndex, ABCPeriodIndex)):
        freq = getattr(data.index, 'freq', None)

        if freq is None:
            freq = getattr(data.index, 'inferred_freq', None)
        if isinstance(freq, DateOffset):
            freq = freq.rule_code

        if freq is None:
            freq = _get_ax_freq(ax)

        if freq is None:
            raise ValueError('Could not get frequency alias for plotting')

        freq = get_base_alias(freq)
        freq = frequencies.get_period_alias(freq)

        if isinstance(data.index, ABCDatetimeIndex):
            data = data.to_period(freq=freq)
        elif isinstance(data.index, ABCPeriodIndex):
            data.index = data.index.asfreq(freq=freq)
    return data
示例#10
0
def _get_period_alias(freq) -> Optional[str]:
    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = base_and_stride(freq)[0]

    freq = get_period_alias(freq)
    return freq
示例#11
0
    def to_period(self, freq=None):
        """
        Cast to PeriodIndex at a particular frequency
        """
        from pandas.tseries.period import PeriodIndex

        if self.freq is None and freq is None:
            msg = "You must pass a freq argument as current index has none."
            raise ValueError(msg)

        if freq is None:
            freq = get_period_alias(self.freqstr)

        return PeriodIndex(self.values, freq=freq)
示例#12
0
    def to_period(self, freq=None):
        """
        Cast to PeriodIndex at a particular frequency
        """
        from pandas.tseries.period import PeriodIndex

        if self.freq is None and freq is None:
            msg = "You must pass a freq argument as current index has none."
            raise ValueError(msg)

        if freq is None:
            freq = get_period_alias(self.freqstr)

        return PeriodIndex(self.values, freq=freq)
示例#13
0
    def _maybe_convert_index(self, data):
        # tsplot converts automatically, but don't want to convert index
        # over and over for DataFrames
        from pandas.core.frame import DataFrame
        if (isinstance(data.index, DatetimeIndex) and
            isinstance(data, DataFrame)):
            freq = getattr(data.index, 'freqstr', None)

            freq = get_period_alias(freq)

            if freq is None and hasattr(data.index, 'inferred_freq'):
                freq = data.index.inferred_freq

            if isinstance(freq, DateOffset):
                freq = freq.rule_code

            data = DataFrame(data.values,
                             index=data.index.to_period(freq=freq),
                             columns=data.columns)
        return data
示例#14
0
def _get_freq(ax, series):
    # get frequency from data
    freq = getattr(series.index, "freq", None)
    if freq is None:
        freq = getattr(series.index, "inferred_freq", None)

    ax_freq = _get_ax_freq(ax)

    # use axes freq if no data freq
    if freq is None:
        freq = ax_freq

    # get the period frequency
    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = get_base_alias(freq)

    freq = frequencies.get_period_alias(freq)
    return freq, ax_freq
示例#15
0
def _maybe_convert_index(ax, data):
    # tsplot converts automatically, but don't want to convert index
    # over and over for DataFrames
    if isinstance(data.index, DatetimeIndex):
        freq = getattr(data.index, 'freq', None)

        if freq is None:
            freq = getattr(data.index, 'inferred_freq', None)
        if isinstance(freq, DateOffset):
            freq = freq.rule_code

        if freq is None:
            freq = getattr(ax, 'freq', None)

        if freq is None:
            raise ValueError('Could not get frequency alias for plotting')

        freq = frequencies.get_base_alias(freq)
        freq = frequencies.get_period_alias(freq)

        data = data.to_period(freq=freq)
    return data
示例#16
0
def tsplot(series, plotf, **kwargs):
    """
    Plots a Series on the given Matplotlib axes or the current axes

    Parameters
    ----------
    axes : Axes
    series : Series

    Notes
    _____
    Supports same kwargs as Axes.plot

    """
    # Used inferred freq is possible, need a test case for inferred
    freq = getattr(series.index, 'freq', None)
    if freq is None and hasattr(series.index, 'inferred_freq'):
        freq = series.index.inferred_freq

    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = frequencies.get_base_alias(freq)

    freq = frequencies.get_period_alias(freq)
    # Convert DatetimeIndex to PeriodIndex
    if isinstance(series.index, DatetimeIndex):
        series = series.to_period(freq=freq)

    if freq != series.index.freq:
        series = series.asfreq(freq)

    style = kwargs.pop('style', None)

    if 'ax' in kwargs:
        ax = kwargs.pop('ax')
    else:
        import matplotlib.pyplot as plt
        ax = plt.gca()

    # Specialized ts plotting attributes for Axes
    ax.freq = freq
    xaxis = ax.get_xaxis()
    xaxis.freq = freq
    xaxis.converter = DateConverter
    ax.legendlabels = [kwargs.get('label', None)]
    ax.view_interval = None
    ax.date_axis_info = None

    # format args and lot
    mask = isnull(series)
    if mask.any():
        masked_array = np.ma.array(series.values)
        masked_array = np.ma.masked_where(mask, masked_array)
        args = [series.index, masked_array]
    else:
        args = [series.index, series]

    if style is not None:
        args.append(style)

    plotf(ax, *args,  **kwargs)

    format_dateaxis(ax, ax.freq)

    left = series.index[0] #get_datevalue(series.index[0], freq)
    right = series.index[-1] #get_datevalue(series.index[-1], freq)
    ax.set_xlim(left, right)

    return ax
示例#17
0
def _get_period_alias(freq) -> Optional[str]:
    freqstr = to_offset(freq).rule_code

    freq = get_period_alias(freqstr)
    return freq
示例#18
0
def _get_period_alias(freq) -> str | None:
    freqstr = to_offset(freq).rule_code

    freq = get_period_alias(freqstr)
    return freq
示例#19
0
    def to_period(self, freq=None):
        """
        Cast to PeriodArray/Index at a particular frequency.

        Converts DatetimeArray/Index to PeriodArray/Index.

        Parameters
        ----------
        freq : string or Offset, optional
            One of pandas' :ref:`offset strings <timeseries.offset_aliases>`
            or an Offset object. Will be inferred by default.

        Returns
        -------
        PeriodArray/Index

        Raises
        ------
        ValueError
            When converting a DatetimeArray/Index with non-regular values,
            so that a frequency cannot be inferred.

        Examples
        --------
        >>> df = pd.DataFrame({"y": [1,2,3]},
        ...                   index=pd.to_datetime(["2000-03-31 00:00:00",
        ...                                         "2000-05-31 00:00:00",
        ...                                         "2000-08-31 00:00:00"]))
        >>> df.index.to_period("M")
        PeriodIndex(['2000-03', '2000-05', '2000-08'],
                    dtype='period[M]', freq='M')

        Infer the daily frequency

        >>> idx = pd.date_range("2017-01-01", periods=2)
        >>> idx.to_period()
        PeriodIndex(['2017-01-01', '2017-01-02'],
                    dtype='period[D]', freq='D')

        See also
        --------
        pandas.PeriodIndex: Immutable ndarray holding ordinal values
        pandas.DatetimeIndex.to_pydatetime: Return DatetimeIndex as object
        """
        from pandas.core.arrays import PeriodArrayMixin

        if self.tz is not None:
            warnings.warn(
                "Converting to PeriodArray/Index representation "
                "will drop timezone information.", UserWarning)

        if freq is None:
            freq = self.freqstr or self.inferred_freq

            if freq is None:
                raise ValueError("You must pass a freq argument as "
                                 "current index has none.")

            freq = get_period_alias(freq)

        return PeriodArrayMixin(self.values, freq=freq)
示例#20
0
文件: plotting.py 项目: manova/pandas
def tsplot(series, plotf, *args, **kwargs):
    """
    Plots a Series on the given Matplotlib axes object

    Parameters
    ----------
    axes : Axes
    series : Series

    Notes
    _____
    Supports same args and kwargs as Axes.plot

    """
    # Used inferred freq is possible, need a test case for inferred
    freq = getattr(series.index, 'freq', None)
    if freq is None and hasattr(series.index, 'inferred_freq'):
        freq = series.index.inferred_freq

    if isinstance(freq, DateOffset):
        freq = freq.rule_code
    else:
        freq = frequencies.get_base_alias(freq)

    freq = frequencies.get_period_alias(freq)
    # Convert DatetimeIndex to PeriodIndex
    if isinstance(series.index, DatetimeIndex):
        series = series.to_period(freq=freq)

    if not isinstance(series.index, PeriodIndex):
        #try to get it to DatetimeIndex then to period
        if series.index.inferred_type == 'datetime':
            idx = DatetimeIndex(series.index).to_period(freq=freq)
            series = Series(series.values, idx, name=series.name)
        else:
            raise TypeError('series argument to tsplot must have '
                            'DatetimeIndex or PeriodIndex')

    if freq != series.index.freq:
        series = series.asfreq(freq)

    style = kwargs.pop('style', None)

    if 'ax' in kwargs:
        ax = kwargs.pop('ax')
    else:
        ax = plt.gca()

    # Specialized ts plotting attributes for Axes
    ax.freq = freq
    xaxis = ax.get_xaxis()
    xaxis.freq = freq
    xaxis.converter = DateConverter
    ax.legendlabels = [kwargs.get('label', None)]
    ax.view_interval = None
    ax.date_axis_info = None

    # format args and lot
    mask = isnull(series)
    if mask.any():
        masked_array = np.ma.array(series.values)
        masked_array = np.ma.masked_where(mask, masked_array)
        args = _check_plot_params(masked_array, series.index, freq, style,
                                  *args)
    else:
        args = _check_plot_params(series, series.index, freq, style, *args)

    plotted = plotf(ax, *args,  **kwargs)

    format_dateaxis(ax, ax.freq)

    # when adding a right axis (using add_yaxis), for some reason the
    # x axis limits don't get properly set. This gets around the problem
    xlim = ax.get_xlim()
    if xlim[0] == 0.0 and xlim[1] == 1.0:
        # if xlim still at default values, autoscale the axis
        ax.autoscale_view()

    left = series.index[0] #get_datevalue(series.index[0], freq)
    right = series.index[-1] #get_datevalue(series.index[-1], freq)
    ax.set_xlim(left, right)

    return plotted
示例#21
0
def _get_period_alias(freq: timedelta | BaseOffset | str) -> str | None:
    freqstr = to_offset(freq).rule_code

    return get_period_alias(freqstr)