当前位置: 首页>>代码示例>>Python>>正文


Python ma.asarray方法代码示例

本文整理汇总了Python中numpy.ma.asarray方法的典型用法代码示例。如果您正苦于以下问题:Python ma.asarray方法的具体用法?Python ma.asarray怎么用?Python ma.asarray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy.ma的用法示例。


在下文中一共展示了ma.asarray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_real_label_width

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def get_real_label_width(self, lev, fmt, fsize):
        """
        This computes actual onscreen label width.
        This uses some black magic to determine onscreen extent of non-drawn
        label.  This magic may not be very robust.

        This method is not being used, and may be modified or removed.
        """
        # Find middle of axes
        xx = np.mean(np.asarray(self.ax.axis()).reshape(2, 2), axis=1)

        # Temporarily create text object
        t = text.Text(xx[0], xx[1])
        self.set_label_props(t, self.get_text(lev, fmt), 'k')

        # Some black magic to get onscreen extent
        # NOTE: This will only work for already drawn figures, as the canvas
        # does not have a renderer otherwise.  This is the reason this function
        # can't be integrated into the rest of the code.
        bbox = t.get_window_extent(renderer=self.ax.figure.canvas.renderer)

        # difference in pixel extent of image
        lw = np.diff(bbox.corners()[0::2, 0])[0]

        return lw 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:27,代码来源:contour.py

示例2: __call__

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def __call__(self, x, clip=None):
        if clip is None:
            clip = self.clip
        x = ma.asarray(x)
        mask = ma.getmaskarray(x)
        xx = x.filled(self.vmax + 1)
        if clip:
            np.clip(xx, self.vmin, self.vmax)
        iret = np.zeros(x.shape, dtype=np.int16)
        for i, b in enumerate(self.boundaries):
            iret[xx >= b] = i
        if self._interp:
            scalefac = float(self.Ncmap - 1) / (self.N - 2)
            iret = (iret * scalefac).astype(np.int16)
        iret[xx < self.vmin] = -1
        iret[xx >= self.vmax] = self.Ncmap
        ret = ma.array(iret, mask=mask)
        if ret.shape == () and not mask:
            ret = int(ret)  # assume python scalar
        return ret 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:22,代码来源:colors.py

示例3: _contour_args

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def _contour_args(self, args, kwargs):
        if self.filled:
            fn = 'contourf'
        else:
            fn = 'contour'
        Nargs = len(args)
        if Nargs <= 2:
            z = ma.asarray(args[0], dtype=np.float64)
            x, y = self._initialize_x_y(z)
            args = args[1:]
        elif Nargs <= 4:
            x, y, z = self._check_xyz(args[:3], kwargs)
            args = args[3:]
        else:
            raise TypeError("Too many arguments to %s; see help(%s)" %
                            (fn, fn))
        z = ma.masked_invalid(z, copy=False)
        self.zmax = float(z.max())
        self.zmin = float(z.min())
        if self.logscale and self.zmin <= 0:
            z = ma.masked_where(z <= 0, z)
            warnings.warn('Log scale: values of z <= 0 have been masked')
            self.zmin = float(z.min())
        self._contour_level_args(z, args)
        return (x, y, z) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:27,代码来源:contour.py

示例4: argstoarray

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def argstoarray(*args):
    """
    Constructs a 2D array from a group of sequences.

    Sequences are filled with missing values to match the length of the longest
    sequence.

    Parameters
    ----------
    args : sequences
        Group of sequences.

    Returns
    -------
    argstoarray : MaskedArray
        A ( `m` x `n` ) masked array, where `m` is the number of arguments and
        `n` the length of the longest argument.

    Notes
    -----
    `numpy.ma.row_stack` has identical behavior, but is called with a sequence
    of sequences.

    """
    if len(args) == 1 and not isinstance(args[0], ndarray):
        output = ma.asarray(args[0])
        if output.ndim != 2:
            raise ValueError("The input should be 2D")
    else:
        n = len(args)
        m = max([len(k) for k in args])
        output = ma.array(np.empty((n,m), dtype=float), mask=True)
        for (k,v) in enumerate(args):
            output[k,:len(v)] = v

    output[np.logical_not(np.isfinite(output._data))] = masked
    return output 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:39,代码来源:mstats_basic.py

示例5: find_repeats

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def find_repeats(arr):
    """Find repeats in arr and return a tuple (repeats, repeat_count).

    The input is cast to float64. Masked values are discarded.

    Parameters
    ----------
    arr : sequence
        Input array. The array is flattened if it is not 1D.

    Returns
    -------
    repeats : ndarray
        Array of repeated values.
    counts : ndarray
        Array of counts.

    """
    # Make sure we get a copy. ma.compressed promises a "new array", but can
    # actually return a reference.
    compr = np.asarray(ma.compressed(arr), dtype=np.float64)
    try:
        need_copy = np.may_share_memory(compr, arr)
    except AttributeError:
        # numpy < 1.8.2 bug: np.may_share_memory([], []) raises,
        # while in numpy 1.8.2 and above it just (correctly) returns False.
        need_copy = False
    if need_copy:
        compr = compr.copy()
    return _find_repeats(compr) 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:32,代码来源:mstats_basic.py

示例6: smooth

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def smooth(self, Z):
        '''Run Unscented Kalman Smoother

        Parameters
        ----------
        Z : [n_timesteps, n_dim_state] array
            Z[t] = observation at time t.  If Z is a masked array and any of
            Z[t]'s elements are masked, the observation is assumed missing and
            ignored.

        Returns
        -------
        smoothed_state_means : [n_timesteps, n_dim_state] array
            filtered_state_means[t] = mean of state distribution at time t given
            observations from times [0, n_timesteps-1]
        smoothed_state_covariances : [n_timesteps, n_dim_state, n_dim_state] array
            filtered_state_covariances[t] = covariance of state distribution at
            time t given observations from times [0, n_timesteps-1]
        '''
        Z = ma.asarray(Z)

        (transition_functions, observation_functions,
         transition_covariance, observation_covariance,
         initial_state_mean, initial_state_covariance) = (
            self._initialize_parameters()
        )

        (filtered_state_means, filtered_state_covariances) = self.filter(Z)
        (smoothed_state_means, smoothed_state_covariances) = (
            additive_unscented_smoother(
                filtered_state_means, filtered_state_covariances,
                transition_functions, transition_covariance
            )
        )

        return (smoothed_state_means, smoothed_state_covariances) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:38,代码来源:unscented.py

示例7: _contour_level_args

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def _contour_level_args(self, z, args):
        """
        Determine the contour levels and store in self.levels.
        """
        if self.filled:
            fn = 'contourf'
        else:
            fn = 'contour'
        self._auto = False
        if self.levels is None:
            if len(args) == 0:
                lev = self._autolev(z, 7)
            else:
                level_arg = args[0]
                try:
                    if type(level_arg) == int:
                        lev = self._autolev(z, level_arg)
                    else:
                        lev = np.asarray(level_arg).astype(np.float64)
                except:
                    raise TypeError(
                        "Last %s arg must give levels; see help(%s)" %
                        (fn, fn))
            self.levels = lev
        if self.filled and len(self.levels) < 2:
            raise ValueError("Filled contours require at least 2 levels.") 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:28,代码来源:contour.py

示例8: _process_levels

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def _process_levels(self):
        """
        Assign values to :attr:`layers` based on :attr:`levels`,
        adding extended layers as needed if contours are filled.

        For line contours, layers simply coincide with levels;
        a line is a thin layer.  No extended levels are needed
        with line contours.
        """
        # The following attributes are no longer needed, and
        # should be deprecated and removed to reduce confusion.
        self.vmin = np.amin(self.levels)
        self.vmax = np.amax(self.levels)

        # Make a private _levels to include extended regions; we
        # want to leave the original levels attribute unchanged.
        # (Colorbar needs this even for line contours.)
        self._levels = list(self.levels)

        if self.extend in ('both', 'min'):
            self._levels.insert(0, min(self.levels[0], self.zmin) - 1)
        if self.extend in ('both', 'max'):
            self._levels.append(max(self.levels[-1], self.zmax) + 1)
        self._levels = np.asarray(self._levels)

        if not self.filled:
            self.layers = self.levels
            return

        # layer values are mid-way between levels
        self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
        # ...except that extended layers must be outside the
        # normed range:
        if self.extend in ('both', 'min'):
            self.layers[0] = -np.inf
        if self.extend in ('both', 'max'):
            self.layers[-1] = np.inf 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:39,代码来源:contour.py

示例9: process_value

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def process_value(value):
        """
        Homogenize the input *value* for easy and efficient normalization.

        *value* can be a scalar or sequence.

        Returns *result*, *is_scalar*, where *result* is a
        masked array matching *value*.  Float dtypes are preserved;
        integer types with two bytes or smaller are converted to
        np.float32, and larger types are converted to np.float.
        Preserving float32 when possible, and using in-place operations,
        can greatly improve speed for large arrays.

        Experimental; we may want to add an option to force the
        use of float32.
        """
        if cbook.iterable(value):
            is_scalar = False
            result = ma.asarray(value)
            if result.dtype.kind == 'f':
                if isinstance(value, np.ndarray):
                    result = result.copy()
            elif result.dtype.itemsize > 2:
                result = result.astype(np.float)
            else:
                result = result.astype(np.float32)
        else:
            is_scalar = True
            result = ma.array([value]).astype(np.float)
        return result, is_scalar 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:32,代码来源:colors.py

示例10: inverse

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def inverse(self, value):
        if not self.scaled():
            raise ValueError("Not invertible until scaled")
        vmin = float(self.vmin)
        vmax = float(self.vmax)

        if cbook.iterable(value):
            val = ma.asarray(value)
            return vmin + val * (vmax - vmin)
        else:
            return vmin + value * (vmax - vmin) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:13,代码来源:colors.py

示例11: __init__

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def __init__(self, boundaries, ncolors, clip=False):
        '''
        *boundaries*
            a monotonically increasing sequence
        *ncolors*
            number of colors in the colormap to be used

        If::

            b[i] <= v < b[i+1]

        then v is mapped to color j;
        as i varies from 0 to len(boundaries)-2,
        j goes from 0 to ncolors-1.

        Out-of-range values are mapped to -1 if low and ncolors
        if high; these are converted to valid indices by
        :meth:`Colormap.__call__` .
        '''
        self.clip = clip
        self.vmin = boundaries[0]
        self.vmax = boundaries[-1]
        self.boundaries = np.asarray(boundaries)
        self.N = len(self.boundaries)
        self.Ncmap = ncolors
        if self.N - 1 == self.Ncmap:
            self._interp = False
        else:
            self._interp = True 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:31,代码来源:colors.py

示例12: argstoarray

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def argstoarray(*args):
    """
    Constructs a 2D array from a group of sequences.

    Sequences are filled with missing values to match the length of the longest
    sequence.

    Parameters
    ----------
    args : sequences
        Group of sequences.

    Returns
    -------
    argstoarray : MaskedArray
        A ( `m` x `n` ) masked array, where `m` is the number of arguments and
        `n` the length of the longest argument.

    Notes
    -----
    numpy.ma.row_stack has identical behavior, but is called with a sequence of
    sequences.

    """
    if len(args) == 1 and not isinstance(args[0], ndarray):
        output = ma.asarray(args[0])
        if output.ndim != 2:
            raise ValueError("The input should be 2D")
    else:
        n = len(args)
        m = max([len(k) for k in args])
        output = ma.array(np.empty((n,m), dtype=float), mask=True)
        for (k,v) in enumerate(args):
            output[k,:len(v)] = v
    output[np.logical_not(np.isfinite(output._data))] = masked
    return output


#####--------------------------------------------------------------------------
#---- --- Ranking ---
#####-------------------------------------------------------------------------- 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:43,代码来源:mstats_basic.py

示例13: ks_twosamp_old

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def ks_twosamp_old(data1, data2):
    """ Computes the Kolmogorov-Smirnov statistic on 2 samples.

    Returns
    -------
    KS D-value, p-value

    """
    (data1, data2) = [ma.asarray(d).compressed() for d in (data1,data2)]
    return stats.ks_2samp(data1,data2)


#####--------------------------------------------------------------------------
#---- --- Trimming ---
#####-------------------------------------------------------------------------- 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:17,代码来源:mstats_basic.py

示例14: trima

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def trima(a, limits=None, inclusive=(True,True)):
    """Trims an array by masking the data outside some given limits.
    Returns a masked version of the input array.

    Parameters
    ----------
    a : sequence
        Input array.
    limits : {None, tuple}, optional
        Tuple of (lower limit, upper limit) in absolute values.
        Values of the input array lower (greater) than the lower (upper) limit
        will be masked. A limit is None indicates an open interval.
    inclusive : {(True,True) tuple}, optional
        Tuple of (lower flag, upper flag), indicating whether values exactly
        equal to the lower (upper) limit are allowed.

    """
    a = ma.asarray(a)
    a.unshare_mask()
    if limits is None:
        return a
    (lower_lim, upper_lim) = limits
    (lower_in, upper_in) = inclusive
    condition = False
    if lower_lim is not None:
        if lower_in:
            condition |= (a < lower_lim)
        else:
            condition |= (a <= lower_lim)
    if upper_lim is not None:
        if upper_in:
            condition |= (a > upper_lim)
        else:
            condition |= (a >= upper_lim)
    a[condition.filled(True)] = masked
    return a 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:38,代码来源:mstats_basic.py

示例15: tsem

# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import asarray [as 别名]
def tsem(a, limits=None, inclusive=(True,True)):
    a = ma.asarray(a).ravel()
    if limits is None:
        n = float(a.count())
        return a.std()/ma.sqrt(n)
    am = trima(a.ravel(), limits, inclusive)
    sd = np.sqrt(am.var())
    return sd / am.count() 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:10,代码来源:mstats_basic.py


注:本文中的numpy.ma.asarray方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。