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

Python toolz.keyfilter函数代码示例

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

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



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

示例1: resource_bcolz

def resource_bcolz(rootdir, **kwargs):
    if os.path.exists(rootdir):
        kwargs = keyfilter(carray_keywords.__contains__, kwargs)
        return ctable(rootdir=rootdir, **kwargs)
    else:
        if 'dshape' in kwargs:
            dtype = to_numpy_dtype(kwargs['dshape'])
            kwargs = keyfilter(carray_keywords.__contains__, kwargs)
            return ctable(np.empty(0, dtype), rootdir=rootdir, **kwargs)
        else:
            raise ValueError("File does not exist and no `dshape=` given")
开发者ID:leolujuyi,项目名称:blaze,代码行数:11,代码来源:bcolz.py


示例2: append_table_to_csv

def append_table_to_csv(csv, selectable, dshape=None, **kwargs):
    kwargs = keyfilter(keywords(CopyToCSV).__contains__,
                       merge(csv.dialect, kwargs))
    stmt = CopyToCSV(selectable, os.path.abspath(csv.path), **kwargs)
    with selectable.bind.connect() as conn:
        conn.execute(stmt)
    return csv
开发者ID:MoherX,项目名称:odo,代码行数:7,代码来源:sql.py


示例3: to_frame

    def to_frame(self, columns=None):
        """
        Make a DataFrame with the given columns.

        Parameters
        ----------
        columns : sequence, optional
            Sequence of the column names desired in the DataFrame.
            If None all columns are returned, including registered columns.

        Returns
        -------
        frame : pandas.DataFrame

        """
        extra_cols = _columns_for_table(self.name)

        if columns:
            local_cols = [c for c in self._frame.columns
                          if c in columns and c not in extra_cols]
            extra_cols = toolz.keyfilter(lambda c: c in columns, extra_cols)
            df = self._frame[local_cols].copy()
        else:
            df = self._frame.copy()

        for name, col in extra_cols.items():
            df[name] = col()

        return df
开发者ID:egeriicw,项目名称:urbansim,代码行数:29,代码来源:simulation.py


示例4: _collect_injectables

def _collect_injectables(names):
    """
    Find all the injectables specified in `names`.

    Parameters
    ----------
    names : list of str

    Returns
    -------
    injectables : dict
        Keys are the names, values are wrappers if the injectable
        is a table. If it's a plain injectable the value itself is given
        or the injectable function is evaluated.

    """
    names = set(names)
    dicts = toolz.keyfilter(
        lambda x: x in names, toolz.merge(_INJECTABLES, _TABLES))

    if set(dicts.keys()) != names:
        raise KeyError(
            'not all injectables found. '
            'missing: {}'.format(names - set(dicts.keys())))

    for name, thing in dicts.items():
        if isinstance(thing, _InjectableFuncWrapper):
            dicts[name] = thing()
        elif isinstance(thing, _TableSourceWrapper):
            dicts[name] = thing.convert()

    return dicts
开发者ID:quintinvh,项目名称:urbansim,代码行数:32,代码来源:simulation.py


示例5: resource_sql

def resource_sql(uri, *args, **kwargs):
    kwargs2 = keyfilter(keywords(sa.create_engine).__contains__, kwargs)
    engine = create_engine(uri, **kwargs2)
    ds = kwargs.get('dshape')
    schema = kwargs.get('schema')

    # we were also given a table name
    if args and isinstance(args[0], (str, unicode)):
        table_name, args = args[0], args[1:]
        metadata = metadata_of_engine(engine, schema=schema)

        with ignoring(sa.exc.NoSuchTableError):
            return attach_schema(sa.Table(table_name, metadata, autoload=True,
                                          autoload_with=engine, schema=schema),
                                 schema)
        if ds:
            t = dshape_to_table(table_name, ds, metadata=metadata)
            t.create()
            return t
        else:
            raise ValueError("Table does not exist and no dshape provided")

    # We were not given a table name
    if ds:
        create_from_datashape(engine, ds, schema=schema)
    return engine
开发者ID:pieterdavid,项目名称:odo,代码行数:26,代码来源:sql.py


示例6: into

def into(a, b, **kwargs):
    dialect = b.dialect.copy()
    del dialect['lineterminator']
    dates = [i for i, typ in enumerate(b.schema[0].types)
               if 'date' in str(typ)]
    schema = b.schema
    if '?' in str(schema):
        schema = dshape(str(schema).replace('?', ''))

    dtypes = valmap(to_numpy_dtype, schema[0].dict)

    datenames = [name for name in dtypes
                      if np.issubdtype(dtypes[name], np.datetime64)]

    dtypes = dict((k, v) for k, v in dtypes.items()
                         if not np.issubdtype(v, np.datetime64))

    if 'strict' in dialect:
        del dialect['strict']

    # Pass only keyword arguments appropriate for read_csv
    kws = keywords(pd.read_csv)
    options = toolz.merge(dialect, kwargs)
    options = toolz.keyfilter(lambda k: k in kws, options)

    if b.open == gzip.open:
        options['compression'] = 'gzip'

    return pd.read_csv(b.path,
                       skiprows=1 if b.header else 0,
                       dtype=dtypes,
                       parse_dates=datenames,
                       names=b.columns,
                       **options)
开发者ID:dalejung,项目名称:blaze,代码行数:34,代码来源:into.py


示例7: pick

def pick(whitelist, d):
    sub = toolz.keyfilter(
        lambda key: key in whitelist, d)
    if isinstance(d, DD):
        return DD(sub)
    else:
        return sub
开发者ID:fashandge,项目名称:deja,代码行数:7,代码来源:utilities.py


示例8: resource_bcolz

def resource_bcolz(uri, dshape=None, **kwargs):
    if os.path.exists(uri):
        return ctable(rootdir=uri)
    else:
        if not dshape:
            raise ValueError("Must specify either existing bcolz directory or"
                    "valid datashape")
        dshape = datashape.dshape(dshape)

        dt = datashape.to_numpy_dtype(dshape)
        x = np.empty(shape=(0,), dtype=dt)

        if datashape.predicates.isrecord(dshape.measure):
            return ctable(x, rootdir=uri, **keyfilter(keywords.__contains__, kwargs))
        else:
            return carray(x, rootdir=uri, **keyfilter(keywords.__contains__, kwargs))
开发者ID:jreback,项目名称:into,代码行数:16,代码来源:bcolz.py


示例9: resource_bcolz

def resource_bcolz(uri, dshape=None, expected_dshape=None, **kwargs):
    if os.path.exists(uri):
        try:
            return ctable(rootdir=uri)
        except IOError:  # __rootdirs__ doesn't exist because we aren't a ctable
            return carray(rootdir=uri)
    else:
        if not dshape:
            raise ValueError("Must specify either existing bcolz directory or"
                             " valid datashape")
        dshape = datashape.dshape(dshape)

        dt = datashape.to_numpy_dtype(dshape)
        shape_tail = tuple(map(int, dshape.shape[1:]))  # tail of shape
        if dshape.shape[0] == datashape.var:
            shape = (0,) + shape_tail
        else:
            shape = (int(dshape.shape[0]),) + shape_tail

        x = np.empty(shape=shape, dtype=dt)

        kwargs = keyfilter(keywords.__contains__, kwargs)
        expectedlen = kwargs.pop('expectedlen',
                                 int(expected_dshape[0])
                                 if expected_dshape is not None and
                                 isinstance(expected_dshape[0], datashape.Fixed)
                                 else None)

        if datashape.predicates.isrecord(dshape.measure):
            return ctable(x, rootdir=uri, expectedlen=expectedlen, **kwargs)
        else:
            return carray(x, rootdir=uri, expectedlen=expectedlen, **kwargs)
开发者ID:mrocklin,项目名称:into,代码行数:32,代码来源:bcolz.py


示例10: details

def details(lat_lon):
    """
    Gives more details about a lat_lon from the lat_lons function.

    """
    return {'location': lat_lon,
            # we remove the events field because it contains some user's name
            'data': keyfilter(lambda k: k != 'events', requests.post(DETAILS, data=lat_lon).json())}
开发者ID:wilbertom,项目名称:formicaria-us,代码行数:8,代码来源:soa_api.py


示例11: into

def into(a, b, **kwargs):
    if isinstance(a, type):
        kwargs = keyfilter(carray_keywords.__contains__, kwargs)
        return carray(b, **kwargs)
    else:
        a.append(b)
        a.flush()
        return a
开发者ID:leolujuyi,项目名称:blaze,代码行数:8,代码来源:bcolz.py


示例12: _build_particles

 def _build_particles(stream_name, parameters, data):
     subset = keyfilter(lambda k: k in parameters, data)
     grouped = OmsExtractor._group_by_timestamp(subset)
     particles = []
     for timestamp, attrs in grouped.iteritems():
         attrs = OmsExtractor._convert_attrs_to_ion(parameters, attrs)
         particles.append(OmsExtractor._build_particle(stream_name, timestamp, attrs))
     return particles
开发者ID:kehunt06,项目名称:mi-instrument,代码行数:8,代码来源:oms_extractor.py


示例13: _csv_to_DataFrame

def _csv_to_DataFrame(c, dshape=None, chunksize=None, **kwargs):
    has_header = kwargs.pop('has_header', c.has_header)
    if has_header is False:
        header = None
    elif has_header is True:
        header = 0
    else:
        header = 'infer'

    sep = kwargs.pop('sep', kwargs.pop('delimiter', c.dialect.get('delimiter', ',')))
    encoding = kwargs.get('encoding', c.encoding)

    if dshape:
        dtypes, parse_dates = dshape_to_pandas(dshape)
        if isrecord(dshape.measure):
            names = kwargs.get('names', dshape.measure.names)
        else:
            names = kwargs.get('names')
    else:
        dtypes = parse_dates = names = None

    usecols = kwargs.pop('usecols', None)
    if parse_dates and usecols:
        parse_dates = [col for col in parse_dates if col in usecols]

    compression = kwargs.pop('compression',
            {'gz': 'gzip', 'bz2': 'bz2'}.get(ext(c.path)))

    # See read_csv docs for header for reasoning
    if names:
        try:
            found_names = pd.read_csv(c.path, encoding=encoding,
                                      compression=compression, nrows=1)
        except StopIteration:
            found_names = pd.read_csv(c.path, encoding=encoding,
                                      compression=compression)
    if names and header == 'infer':
        if [n.strip() for n in found_names] == [n.strip() for n in names]:
            header = 0
        elif (all(re.match('^\s*\D\w*\s*$', n) for n in found_names) and
                not all(dt == datashape.string for dt in dshape.measure.types)):
            header = 0
        else:
            header = None

    kwargs2 = keyfilter(keywords(pandas.read_csv).__contains__, kwargs)
    return pandas.read_csv(c.path,
                             header=header,
                             sep=sep,
                             encoding=encoding,
                             dtype=dtypes,
                             parse_dates=parse_dates,
                             names=names,
                             compression=compression,
                             chunksize=chunksize,
                             usecols=usecols,
                             **kwargs2)
开发者ID:mrocklin,项目名称:into,代码行数:57,代码来源:csv.py


示例14: get_test_cases

def get_test_cases(task):
    kwarglist = toolz.keyfilter(lambda x: x != "return",
                                task.run.__annotations__)
    if kwarglist:
        value = next(kwarglist.itervalues())
        return [toolz.valmap(lambda x: x[i], kwarglist)
                for i in xrange(len(value))]
    else:
        return [{}]
开发者ID:mhdann,项目名称:tdi_projects,代码行数:9,代码来源:validate.py


示例15: _csv_to_dataframe

def _csv_to_dataframe(c, dshape=None, chunksize=None, **kwargs):
    header = {False: None, True: 0}.get(
        kwargs.pop('has_header', c.has_header), 'infer')

    sep = kwargs.pop(
        'sep', kwargs.pop('delimiter', c.dialect.get('delimiter', ',')))
    encoding = kwargs.pop('encoding', c.encoding)

    if dshape:
        dtypes, parse_dates = dshape_to_pandas(dshape)
        if isrecord(dshape.measure):
            names = kwargs.get('names', dshape.measure.names)
        else:
            names = kwargs.get('names')
    else:
        dtypes = parse_dates = names = None

    usecols = kwargs.pop('usecols', None)
    if parse_dates and usecols:
        parse_dates = [col for col in parse_dates if col in usecols]

    # See read_csv docs for header for reasoning
    if names:
        try:
            with c.open() as f:
                found_names = pd.read_csv(f,
                                          nrows=1,
                                          encoding=encoding,
                                          sep=sep)
        except StopIteration:
            with c.open() as f:
                found_names = pd.read_csv(f, encoding=encoding, sep=sep)
    if names and header == 'infer':
        if [n.strip() for n in found_names] == [n.strip() for n in names]:
            header = 0
        elif (all(re.match('^\s*\D\w*\s*$', n) for n in found_names) and
                not all(dt == datashape.string for dt in dshape.measure.types)):
            header = 0
        else:
            header = None

    kwargs = keyfilter(keywords(pd.read_csv).__contains__, kwargs)
    with c.open() as f:
        return pd.read_csv(f,
                           header=header,
                           sep=sep,
                           encoding=encoding,
                           dtype=dtypes,
                           parse_dates=parse_dates,
                           names=names,
                           chunksize=chunksize,
                           usecols=usecols,
                           **kwargs)
开发者ID:Curezhang,项目名称:odo,代码行数:53,代码来源:csv.py


示例16: _csv_to_dataframe

def _csv_to_dataframe(c, dshape=None, chunksize=None, **kwargs):
    header = {False: None, True: 0}.get(kwargs.pop("has_header", c.has_header), "infer")

    sep = kwargs.pop("sep", kwargs.pop("delimiter", c.dialect.get("delimiter", ",")))
    encoding = kwargs.pop("encoding", c.encoding)

    if dshape:
        dtypes, parse_dates = dshape_to_pandas(dshape)
        if isrecord(dshape.measure):
            names = kwargs.get("names", dshape.measure.names)
        else:
            names = kwargs.get("names")
    else:
        dtypes = parse_dates = names = None

    usecols = kwargs.pop("usecols", None)
    if parse_dates and usecols:
        parse_dates = [col for col in parse_dates if col in usecols]

    compression = kwargs.pop("compression", {"gz": "gzip", "bz2": "bz2"}.get(ext(c.path)))

    # See read_csv docs for header for reasoning
    if names:
        try:
            found_names = pd.read_csv(c.path, encoding=encoding, compression=compression, nrows=1)
        except StopIteration:
            found_names = pd.read_csv(c.path, encoding=encoding, compression=compression)
    if names and header == "infer":
        if [n.strip() for n in found_names] == [n.strip() for n in names]:
            header = 0
        elif all(re.match("^\s*\D\w*\s*$", n) for n in found_names) and not all(
            dt == datashape.string for dt in dshape.measure.types
        ):
            header = 0
        else:
            header = None

    kwargs = keyfilter(keywords(pd.read_csv).__contains__, kwargs)
    return pd.read_csv(
        c.path,
        header=header,
        sep=sep,
        encoding=encoding,
        dtype=dtypes,
        parse_dates=parse_dates,
        names=names,
        compression=compression,
        chunksize=chunksize,
        usecols=usecols,
        **kwargs
    )
开发者ID:sandhujasmine,项目名称:odo,代码行数:51,代码来源:csv.py


示例17: get_prox_infos

def get_prox_infos(proxes, keys=None):
    if keys is None:
        keys = ['time', 'iter']

    pred = lambda x: x in keys

    out = []
    for prox in proxes:
        if hasattr(prox, 'info'):
            out += [keyfilter(pred, prox.info)]
        else:
            out += [None]

    return out
开发者ID:ajfriend,项目名称:admm,代码行数:14,代码来源:admm.py


示例18: from_transposon_fusion

    def from_transposon_fusion(cls, fusion, id_=None, drop_metadata=None):
        """Converts (annotated) transposon fusion to an insertion.

        Requires

        Parameters
        ----------
        id : str
            ID to use for the insertion.

        Returns
        -------
        Insertion
            Insertion object derived from the transposon fusion.

        """

        if drop_metadata is None:
            drop_metadata = {'strand_genome', 'strand_transposon'}

        # Fusion should have annotated transposon feature.
        if 'feature_name' not in fusion.metadata:
            raise ValueError(
                'Fusion does not have an annotated transposon feature')

        strand = fusion.strand_genome * fusion.strand_transposon

        if 'gene_strand' in fusion.metadata:
            gene_strand = fusion.metadata['gene_strand']
            orientation = 'sense' if strand == gene_strand else 'antisense'
        else:
            orientation = None

        ins_metadata = toolz.keyfilter(lambda k: k not in drop_metadata,
                                       fusion.metadata)
        ins_metadata['transposon_anchor'] = fusion.anchor_transposon

        if orientation is not None:
            ins_metadata['orientation'] = orientation

        return Insertion(
            id=id_,
            seqname=fusion.seqname,
            position=fusion.anchor_genome,
            strand=strand,
            support_junction=fusion.support_junction,
            support_spanning=fusion.support_spanning,
            support=fusion.support,
            metadata=frozendict(ins_metadata))
开发者ID:jrderuiter,项目名称:im-fusion,代码行数:49,代码来源:model.py


示例19: dataset_from_dshape

def dataset_from_dshape(file, datapath, ds, **kwargs):
    dtype = varlen_dtype(to_numpy_dtype(ds))
    if datashape.var not in list(ds):
        shape = to_numpy(ds)[0]
    elif len(ds.shape) == 1:
        shape = (0,)
    else:
        raise ValueError("Don't know how to handle varlen nd shapes")

    if shape:
        kwargs['chunks'] = kwargs.get('chunks', True)
        kwargs['maxshape'] = kwargs.get('maxshape', (None,) + shape[1:])

    kwargs2 = keyfilter(h5py_attributes.__contains__, kwargs)
    return file.require_dataset(datapath, shape=shape, dtype=dtype, **kwargs2)
开发者ID:leolujuyi,项目名称:blaze,代码行数:15,代码来源:h5py.py


示例20: filter_kwargs

def filter_kwargs(f, kwargs):
    """Return a dict of valid kwargs for `f` from a subset of `kwargs`

    Examples
    --------
    >>> def f(a, b=1, c=2):
    ...     return a + b + c
    ...
    >>> raw_kwargs = dict(a=1, b=3, d=4)
    >>> f(**raw_kwargs)
    Traceback (most recent call last):
        ...
    TypeError: f() got an unexpected keyword argument 'd'
    >>> kwargs = filter_kwargs(f, raw_kwargs)
    >>> f(**kwargs)
    6
    """
    return keyfilter(keywords(f).__contains__, kwargs)
开发者ID:kwin-wang,项目名称:odo,代码行数:18,代码来源:utils.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python toolz.keymap函数代码示例发布时间:2022-05-27
下一篇:
Python toolz.join函数代码示例发布时间: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