• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python cbook.iterable函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.cbook.iterable函数的典型用法代码示例。如果您正苦于以下问题:Python iterable函数的具体用法?Python iterable怎么用?Python iterable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: hist

 def hist(self, x, **kwargs):  # pylint: disable=arguments-differ
     if iterable(x) and not numpy.size(x):
         x = numpy.ndarray((0,))
     logbins = kwargs.pop('logbins', False)
     bins = kwargs.get('bins', 30)
     weights = kwargs.get('weights', None)
     if isinstance(weights, (float, int)):
         if isinstance(x, numpy.ndarray) or not iterable(x[0]):
             kwargs['weights'] = numpy.ones_like(x) * weights
         else:
             kwargs['weights'] = []
             for arr in x:
                 kwargs['weights'].append(numpy.ones_like(arr) * weights)
             kwargs['weights'] = numpy.asarray(kwargs['weights'])
     if logbins and (bins is None or isinstance(bins, (float, int))):
         bins = bins or 30
         range_ = kwargs.pop('range', self.common_limits(x))
         if range_[1] == range_[0]:
             kwargs['bins'] = bins
         else:
             kwargs['bins'] = self.bin_boundaries(range_[0], range_[1],
                                                  bins, log=True)
     if kwargs.get('histtype', None) == 'stepfilled':
         kwargs.setdefault('edgecolor', 'black')
     return super(HistogramAxes, self).hist(x, **kwargs)
开发者ID:stefco,项目名称:gwpy,代码行数:25,代码来源:histogram.py


示例2: fetch_historical_yahoo

def fetch_historical_yahoo(ticker, date1, date2, cachename=None,dividends=False):
    """
    Fetch historical data for ticker between date1 and date2.  date1 and
    date2 are date or datetime instances, or (year, month, day) sequences.

    Ex:
    fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))

    cachename is the name of the local file cache.  If None, will
    default to the md5 hash or the url (which incorporates the ticker
    and date range)
    
    set dividends=True to return dividends instead of price data.  With
    this option set, parse functions will not work

    a file handle is returned
    """

    ticker = ticker.upper()


    if iterable(date1):
        d1 = (date1[1]-1, date1[2], date1[0])
    else:
        d1 = (date1.month-1, date1.day, date1.year)
    if iterable(date2):
        d2 = (date2[1]-1, date2[2], date2[0])
    else:
        d2 = (date2.month-1, date2.day, date2.year)


    if dividends:
        g='v'
        verbose.report('Retrieving dividends instead of prices')
    else:
        g='d'

    urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv'


    url =  urlFmt % (d1[0], d1[1], d1[2],
                     d2[0], d2[1], d2[2], ticker, g)


    if cachename is None:
        cachename = os.path.join(cachedir, md5(url).hexdigest())
    if os.path.exists(cachename):
        fh = open(cachename)
        verbose.report('Using cachefile %s for %s'%(cachename, ticker))
    else:
        mkdirs(cachedir)
        urlfh = urlopen(url)

        fh = open(cachename, 'wb')
        fh.write(urlfh.read())
        fh.close()
        verbose.report('Saved %s data to cache file %s'%(ticker, cachename))
        fh = open(cachename, 'r')

    return fh
开发者ID:BlackEarth,项目名称:portable-python-win32,代码行数:60,代码来源:finance.py


示例3: from_list

    def from_list(name, colors, N=256, gamma=1.0):
        """
        Make a linear segmented colormap with *name* from a sequence
        of *colors* which evenly transitions from colors[0] at val=0
        to colors[-1] at val=1.  *N* is the number of rgb quantization
        levels.
        Alternatively, a list of (value, color) tuples can be given
        to divide the range unevenly.
        """

        if not cbook.iterable(colors):
            raise ValueError('colors must be iterable')

        if cbook.iterable(colors[0]) and len(colors[0]) == 2 and \
                not cbook.is_string_like(colors[0]):
            # List of value, color pairs
            vals, colors = zip(*colors)
        else:
            vals = np.linspace(0., 1., len(colors))

        cdict = dict(red=[], green=[], blue=[])
        for val, color in zip(vals, colors):
            r,g,b = colorConverter.to_rgb(color)
            cdict['red'].append((val, r, r))
            cdict['green'].append((val, g, g))
            cdict['blue'].append((val, b, b))

        return LinearSegmentedColormap(name, cdict, N, gamma)
开发者ID:blitzmann,项目名称:Pyfa-skel,代码行数:28,代码来源:colors.py


示例4: getStock

def getStock(ticker, d1, d2, verbose=False):
    if not iterable(d1): d1 = (d1, 1, 1)
    if not iterable(d2): d2 = (d2, 1, 1)

    saveStock(ticker, d1, d2)

    pickleFile = "%s/%s.pklz" % (storageDir, ticker)

    d = { }
    d["days"] = { }
    try:
        fh = gzip.open(pickleFile, "rb")
        dOld = pickle.load(fh)
        fh.close()
    except:
        if(verbose): print "[MM] Error: file (%s/%s.pklz) does not exist" % (storageDir, ticker)
        return d


    dt1, dt2 = datetime.datetime(*d1), datetime.datetime(*d2)
    day1, day2 = u.tuple2inum(d1), u.tuple2inum(d2)

    for day in dOld["days"].keys():
        if( day1 <= day <= day2 ):
            d["days"][day] = dOld["days"][day]

    return d
开发者ID:aminnj,项目名称:makers,代码行数:27,代码来源:getStocks.py


示例5: add_lines

    def add_lines(self, levels, colors, linewidths, erase=True):
        """
        Draw lines on the colorbar.

        *colors* and *linewidths* must be scalars or
        sequences the same length as *levels*.

        Set *erase* to False to add lines without first
        removing any previously added lines.
        """
        y = self._locate(levels)
        igood = (y < 1.001) & (y > -0.001)
        y = y[igood]
        if cbook.iterable(colors):
            colors = np.asarray(colors)[igood]
        if cbook.iterable(linewidths):
            linewidths = np.asarray(linewidths)[igood]
        N = len(y)
        x = np.array([0.0, 1.0])
        X, Y = np.meshgrid(x, y)
        if self.orientation == "vertical":
            xy = [list(zip(X[i], Y[i])) for i in range(N)]
        else:
            xy = [list(zip(Y[i], X[i])) for i in range(N)]
        col = collections.LineCollection(xy, linewidths=linewidths)

        if erase and self.lines:
            for lc in self.lines:
                lc.remove()
            self.lines = []
        self.lines.append(col)
        col.set_color(colors)
        self.ax.add_collection(col)
开发者ID:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:33,代码来源:colorbar.py


示例6: _fetch_historical_yahoo

    def _fetch_historical_yahoo(self, ticker, date1, date2, freq=None, cachename=None):
        """matplotlib's implementation, modified to provide proxy support and frequency
        Fetch historical data for ticker between date1 and date2.  date1 and
        date2 are date or datetime instances, or (year, month, day) sequences.

        Ex:
        fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31))

        cachename is the name of the local file cache.  If None, will
        default to the md5 hash or the url (which incorporates the ticker
        and date range)

        a file handle is returned
        """
        if freq is None or type(freq) != str:
            raise ValueError('Must enter a frequency as a string, m, w, or d')

        proxy = self._proxy
        ticker = ticker.upper()
        
        configdir = get_configdir()
        cachedir = os.path.join(configdir, 'finance.cache')

        if iterable(date1):
            d1 = (date1[1]-1, date1[2], date1[0])
        else:
            d1 = (date1.month-1, date1.day, date1.year)
        if iterable(date2):
            d2 = (date2[1]-1, date2[2], date2[0])
        else:
            d2 = (date2.month-1, date2.day, date2.year)

        urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv'

        url =  urlFmt % (d1[0], d1[1], d1[2],
                         d2[0], d2[1], d2[2], ticker, freq)

        if proxy:
            proxy_support = urllib2.ProxyHandler(proxy)
            opener = urllib2.build_opener(proxy_support)
            urllib2.install_opener(opener)

        if cachename is None:
            cachename = os.path.join(cachedir, md5(url).hexdigest())
        if os.path.exists(cachename):
            fh = file(cachename)
            verbose.report('Using cachefile %s for %s'%(cachename, ticker))
        else:
            if not os.path.isdir(cachedir):
                os.mkdir(cachedir)
            urlfh = urllib2.urlopen(url)

            fh = file(cachename, 'w')
            fh.write(urlfh.read())
            fh.close()
            verbose.report('Saved %s data to cache file %s'%(ticker, cachename))
            fh = file(cachename, 'r')

        return fh
开发者ID:divieira,项目名称:covshrink,代码行数:59,代码来源:inspricehist.py


示例7: plot

    def plot(self, xs, ys, *args, **kwargs):
        '''
        Plot 2D or 3D data.

        ==========  ================================================
        Argument    Description
        ==========  ================================================
        *xs*, *ys*  X, y coordinates of vertices

        *zs*        z value(s), either one for all points or one for
                    each point.
        *zdir*      Which direction to use as z ('x', 'y' or 'z')
                    when plotting a 2d set.
        ==========  ================================================

        Other arguments are passed on to
        :func:`~matplotlib.axes.Axes.plot`
        '''
        # FIXME: This argument parsing might be better handled
        #        when we set later versions of python for
        #        minimum requirements.  Currently at 2.4.
        #        Note that some of the reason for the current difficulty
        #        is caused by the fact that we want to insert a new
        #        (semi-optional) positional argument 'Z' right before
        #        many other traditional positional arguments occur
        #        such as the color, linestyle and/or marker.
        had_data = self.has_data()
        zs = kwargs.pop('zs', 0)
        zdir = kwargs.pop('zdir', 'z')

        argsi = 0
        # First argument is array of zs
        if len(args) > 0 and cbook.iterable(args[0]) and \
                len(xs) == len(args[0]) :
            # So, we know that it is an array with
            # first dimension the same as xs.
            # Next, check to see if the data contained
            # therein (if any) is scalar (and not another array).
            if len(args[0]) == 0 or cbook.is_scalar(args[0][0]) :
                zs = args[argsi]
                argsi += 1

        # First argument is z value
        elif len(args) > 0 and cbook.is_scalar(args[0]):
            zs = args[argsi]
            argsi += 1

        # Match length
        if not cbook.iterable(zs):
            zs = np.ones(len(xs)) * zs

        lines = Axes.plot(self, xs, ys, *args[argsi:], **kwargs)
        for line in lines:
            art3d.line_2d_to_3d(line, zs=zs, zdir=zdir)

        self.auto_scale_xyz(xs, ys, zs, had_data)
        return lines
开发者ID:dhomeier,项目名称:matplotlib-py3,代码行数:57,代码来源:axes3d.py


示例8: append_fields

    def append_fields(rec, names, arr, dtype=None):
        """
        Appends a field to an existing record array, handling masked fields
        if necessary.

        Parameters
        ----------
        rec : numpy record array
            Array to which the new field should be appended
        names : string
            Names to be given to the new fields
        arr : ndarray
            Array containing the data for the new fields.
        dtype : data-type or None, optional
            Data type of the new fields.  If this is None, the data types will
            be obtained from `arr`.

        Returns
        -------
        out : numpy record array
            `rec` with the new field appended.
        rec = append_fields(rec, name, arr)
        """
        if not iterable(names):
            names = [names]
        if not iterable(arr):
            arr = [arr]

        if dtype is None:
            dtype = [a.dtype for a in arr]

        newdtype = np.dtype(rec.dtype.descr + zip(names, dtype))
        newrec = np.empty(rec.shape, dtype=newdtype).view(type(rec))

        for name in rec.dtype.names:
            newrec[name] = rec[name]
            try:
                newrec.mask[name] = rec.mask[name]
            except AttributeError:
                pass #Not a masked array

        for n,a in zip(names, arr):
            newrec[n] = a
            try:
                old_mask = a.mask
            except AttributeError:
                old_mask = np.array([False]*a.size).reshape(a.shape)
            try:
                newrec[n].mask = old_mask
            except AttributeError:
                pass
        return newrec
开发者ID:rayg-ssec,项目名称:MetPy,代码行数:52,代码来源:cbook.py


示例9: getTimeIntervall

def getTimeIntervall(stream, start=None, end=None, relative='starttime', ret_rel='utc'):
    """
    Create two lists of UTCDateTimes - start list and end list

    'time' can stand for UTCDateTime, list of UTCDateTimes, header entry out of
    ('ponset', 'sonset', 'startime', 'endtime') or 'middle'
    :param start, end: - None (means start- resp. endtime)
        - time object
        - or seconds relative to param relative
    :param relative: times (if given as seconds=numbers) are taken relative to
        this parameter, is also needed for param ret_rel='relative
        -time object
    :param ret_rel: - 'utc'  output in absolute UTCDateTime
        - 'relative': output in seconds relative to param relative
        - time object: output in seconds relative to time
    :return: start and end list of UTCDateTime or None if stream has length 0
    """
    N = len(stream)
    if N == 0:
        return

    # get list of UTCDateTimes for start_out and end_out
    if start == None:
        start = 'starttime'
    if end == None:
        end = 'endtime'
    start_out = _getUTCListFromSth(stream, start)
    end_out = _getUTCListFromSth(stream, end)

    # get list of UTCDateTimes for relative if needed
    if start_out == None or end_out == None or ret_rel == 'relative':
        relative = _getUTCListFromSth(stream, relative, raisenumber=True)
    # get list of UTCDateTimes for start_out and end_out
    if start_out == None:
        if cbook.iterable(start):
            start_out = [utc + start[i] for i, utc in enumerate(relative)]
        else:
            start_out = [i + start for i in relative]
    if end_out == None:
        if cbook.iterable(start):
            end_out = [utc + end[i] for i, utc in enumerate(relative)]
        else:
            end_out = [i + end for i in relative]

    # convert UTCDateTimes to seconds if ret_rel demands it
    if ret_rel == 'utc':
        return start_out, end_out
    elif ret_rel != 'relative':
        relative = _getUTCListFromSth(stream, ret_rel)
    start_out = [start_out[i] - relative[i] for i in range(N)]
    end_out = [end_out[i] - relative[i] for i in range(N)]
    return start_out, end_out
开发者ID:iceseismic,项目名称:sito,代码行数:52,代码来源:imaging.py


示例10: wsat

def wsat(Temp, press):
    """
    wsat(Temp, press)

    Calculates the saturation vapor mixing ratio of an air parcel.

    Parameters
    - - - - - -
    Temp : float or array_like
        Temperature in Kelvin.
    press : float or array_like
        Pressure in Pa.

    Returns
    - - - -
    theWs : float or array_like 
        Saturation water vapor mixing ratio in (kg/kg).

    Raises
    - - - -
    IOError
        If both 'Temp' and 'press' are array_like.

    Examples
    - - - - -
    >>> test.assert_almost_equal(wsat(300, 8e4),0.02875,decimal=4)
    >>> test.assert_array_almost_equal(wsat([300,310], 8e4),[0.0287, 0.0525],decimal=4)
    >>> test.assert_array_almost_equal(wsat(300, [8e4, 7e4]),[0.0287, 0.0330],decimal=4)
    >>> wsat([300, 310], [8e4, 7e4])
    Traceback (most recent call last):
        ...
    IOError: Can't have two vector inputs.

    """
    is_scalar_temp=True
    if cbook.iterable(Temp):
        is_scalar_temp = False
    is_scalar_press=True
    if cbook.iterable(press):
        is_scalar_press = False
    Temp=np.atleast_1d(Temp)
    press=np.atleast_1d(press)
    if (np.size(Temp) !=1) and (np.size(press) != 1):
        raise IOError, "Can't have two vector inputs."
    es = esat(Temp);
    theWs=(c.eps * es/ (press - es))
    theWs[theWs > 0.060]=0.06
    theWs[theWs < 0.0] = 0.
    if is_scalar_temp and is_scalar_press:
        theWs=theWs[0]
    return theWs
开发者ID:phaustin,项目名称:pythermo,代码行数:51,代码来源:new_thermo.py


示例11: __call__

    def __call__(self, value, clip=None):
        if clip is None:
            clip = self.clip

        if cbook.iterable(value):
            vtype = 'array'
            val = np.ma.asarray(value).astype(np.float)
        else:
            vtype = 'scalar'
            val = np.ma.array([value]).astype(np.float)

        self.autoscale_None(val)

        vmin, vmax = float(self.vmin), float(self.vmax)
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin==vmax:
            return 0.0 * val
        else:
            if clip:
                mask = np.ma.getmask(val)
                val = np.ma.array(np.clip(val.filled(vmax), vmin, vmax),
                                   mask=mask)
            result = np.ma.array(np.interp(val, self.xval, self.yval),
                                  mask=np.ma.getmask(val))
            result[np.isinf(val.data)] = -np.inf
        if vtype == 'scalar':
            result = result[0]
        return result
开发者ID:montefra,项目名称:healpy,代码行数:29,代码来源:projaxes.py


示例12: __call__

    def __call__(self, value, clip=None):
        if clip is None:
            clip = self.clip

        if cbook.iterable(value):
            vtype = 'array'
            val = ma.asarray(value).astype(np.float)
        else:
            vtype = 'scalar'
            val = ma.array([value]).astype(np.float)

        self.autoscale_None(val)
        vmin, vmax = self.vmin, self.vmax
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin<=0:
            raise ValueError("values must all be positive")
        elif vmin==vmax:
            return 0.0 * val
        else:
            if clip:
                mask = ma.getmask(val)
                val = ma.array(np.clip(val.filled(vmax), vmin, vmax),
                                mask=mask)
            result = (ma.log(val)-np.log(vmin))/(np.log(vmax)-np.log(vmin))
        if vtype == 'scalar':
            result = result[0]
        return result
开发者ID:AndreI11,项目名称:SatStressGui,代码行数:28,代码来源:colors.py


示例13: __init__

    def __init__(self, artists, tolerance=5, offsets=(-20, 20), template="x: %0.2f\ny: %0.2f", display_all=False):
        """Create the data cursor and connect it to the relevant figure.
        "artists" is the matplotlib artist or sequence of artists that will be 
            selected. 
        "tolerance" is the radius (in points) that the mouse click must be
            within to select the artist.
        "offsets" is a tuple of (x,y) offsets in points from the selected
            point to the displayed annotation box
        "template" is the format string to be used. Note: For compatibility
            with older versions of python, this uses the old-style (%) 
            formatting specification.
        "display_all" controls whether more than one annotation box will
            be shown if there are multiple axes.  Only one will be shown
            per-axis, regardless. 
        """
        self.template = template
        self.offsets = offsets
        self.display_all = display_all
        if not cbook.iterable(artists):
            artists = [artists]
        self.artists = artists
        self.axes = tuple(set(art.axes for art in self.artists))
        self.figures = tuple(set(ax.figure for ax in self.axes))

        self.annotations = {}
        for ax in self.axes:
            self.annotations[ax] = self.annotate(ax)

        for artist in self.artists:
            artist.set_picker(tolerance)
        for fig in self.figures:
            fig.canvas.mpl_connect("pick_event", self)
开发者ID:timvieira,项目名称:viz,代码行数:32,代码来源:datacursor.py


示例14: hist

def hist(*args, **kwargs):
    """
    Plots a histogram of the provided data. Can provide optional argument
    "grid='x'" or "grid='y'" to draw a white grid over the histogram. Almost like "erasing" some of the plot,
     but it adds more information!
    """
    ax, args, kwargs = maybe_get_ax(*args, **kwargs)

    color_cycle = ax._get_lines.color_cycle
    # Reassign the default colors to Set2 by Colorbrewer
    if iterable(args[0]):
        if isinstance(args[0], list):
            ncolors = len(args[0])
        else:
            if len(args[0].shape) == 2:
                ncolors = args[0].shape[1]
            else:
                ncolors = 1
        kwargs.setdefault('color', [next(color_cycle) for _ in range(ncolors)])
    else:
        kwargs.setdefault('color', next(color_cycle))
    kwargs.setdefault('edgecolor', 'white')
    show_ticks = kwargs.pop('show_ticks', False)

    # If no grid specified, don't draw one.
    grid = kwargs.pop('grid', None)

    # print 'hist kwargs', kwargs
    patches = ax.hist(*args, **kwargs)
    remove_chartjunk(ax, ['top', 'right'], grid=grid, show_ticks=show_ticks)
    return ax
开发者ID:Mrngilles,项目名称:prettyplotlib,代码行数:31,代码来源:_hist.py


示例15: __init__

    def __init__(self, artists, x = [], y = [], tolerance = 5, offsets = (-20, 20),
                 formatter = fmt, display_all = False):
        """Create the data cursor and connect it to the relevant figure.
        "artists" is the matplotlib artist or sequence of artists that will be 
            selected. 
        "tolerance" is the radius (in points) that the mouse click must be
            within to select the artist.
        "offsets" is a tuple of (x,y) offsets in points from the selected
            point to the displayed annotation box
        "formatter" is a callback function which takes 2 numeric arguments and
            returns a string
        "display_all" controls whether more than one annotation box will
            be shown if there are multiple axes.  Only one will be shown
            per-axis, regardless. 
        """
        self._points = np.column_stack((x,y))
        self.formatter = formatter
        self.offsets = offsets
        self.display_all = display_all
        if not cbook.iterable(artists):
            artists = [artists]
        self.artists = artists
        self.axes = tuple(set(art.axes for art in self.artists))
        self.figures = tuple(set(ax.figure for ax in self.axes))

        self.annotations = {}
        for ax in self.axes:
            self.annotations[ax] = self.annotate(ax)

        for artist in self.artists:
            artist.set_picker(tolerance)
        for fig in self.figures:
            fig.canvas.mpl_connect('pick_event', self)
开发者ID:episodeyang,项目名称:EonHe-Trap-Analysis,代码行数:33,代码来源:data_cursor_example.py


示例16: get_converter

    def get_converter(self, x):
        'get the converter interface instance for x, or None'

        if not len(self): return None # nothing registered
        #DISABLED idx = id(x)
        #DISABLED cached = self._cached.get(idx)
        #DISABLED if cached is not None: return cached

        converter = None
        classx = getattr(x, '__class__', None)

        if classx is not None:
            converter = self.get(classx)

        # Check explicity for strings here because they would otherwise
        # lead to an infinite recursion, because a single character will
        # pass the iterable() check.
        if converter is None and iterable(x) and not is_string_like(x):
            # if this is anything but an object array, we'll assume
            # there are no custom units
            if isinstance(x, np.ndarray) and x.dtype != np.object:
                return None

            for thisx in x:
                converter = self.get_converter( thisx )
                return converter

        #DISABLED self._cached[idx] = converter
        return converter
开发者ID:zoccolan,项目名称:eyetracker,代码行数:29,代码来源:units.py


示例17: convert

 def convert(val, unit, axis):
     if units.ConversionInterface.is_numlike(val):
         return val
     if iterable(val):
         return [thisval.convert_to(unit).get_value() for thisval in val]
     else:
         return val.convert_to(unit).get_value()
开发者ID:HDembinski,项目名称:matplotlib,代码行数:7,代码来源:basic_units.py


示例18: _determine_lims

 def _determine_lims(self, xmin=None, xmax=None, *args, **kwargs):
     if xmax is None and cbook.iterable(xmin):
         xmin, xmax = xmin
     if xmin == xmax:
         xmin -= 0.5
         xmax += 0.5
     return (xmin, xmax)
开发者ID:CTPUG,项目名称:matplotlib,代码行数:7,代码来源:axes3d.py


示例19: common_limits

    def common_limits(datasets, default_min=0, default_max=0):
        """Find the global maxima and minima of a list of datasets.

        Parameters
        ----------
        datasets : `iterable`
            list (or any other iterable) of data arrays to analyse.

        default_min : `float`, optional
            fall-back minimum value if datasets are all empty.

        default_max : `float`, optional
            fall-back maximum value if datasets are all empty.

        Returns
        -------
        (min, max) : `float`
            2-tuple of common minimum and maximum over all datasets.
        """
        from glue import iterutils
        if isinstance(datasets, numpy.ndarray) or not iterable(datasets[0]):
            datasets = [datasets]
        max_stat = max(list(iterutils.flatten(datasets)) + [-numpy.inf])
        min_stat = min(list(iterutils.flatten(datasets)) + [numpy.inf])
        if numpy.isinf(-max_stat):
            max_stat = default_max
        if numpy.isinf(min_stat):
            min_stat = default_min
        return min_stat, max_stat
开发者ID:stefco,项目名称:gwpy,代码行数:29,代码来源:histogram.py


示例20: get_converter

    def get_converter(self, x):
        'get the converter interface instance for x, or None'

        if not len(self): return None # nothing registered
        #DISABLED idx = id(x)
        #DISABLED cached = self._cached.get(idx)
        #DISABLED if cached is not None: return cached

        converter = None
        classx = getattr(x, '__class__', None)

        if classx is not None:
            converter = self.get(classx)

        if converter is None and iterable(x):
            for thisx in x:
                # Make sure that recursing might actually lead to a solution, if
                # we are just going to re-examine another item of the same kind,
                # then do not look at it.
                if classx and classx != getattr(thisx, '__class__', None):
                    converter = self.get_converter( thisx )
                    return converter

        #DISABLED self._cached[idx] = converter
        return converter
开发者ID:AlexSzatmary,项目名称:matplotlib,代码行数:25,代码来源:units.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python cbook.listFiles函数代码示例发布时间:2022-05-27
下一篇:
Python cbook.issubclass_safe函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap