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


Python compat.map方法代码示例

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


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

示例1: test_to_excel_multiindex_cols

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def test_to_excel_multiindex_cols(self, merge_cells, engine, ext):
        frame = self.frame
        arrays = np.arange(len(frame.index) * 2).reshape(2, -1)
        new_index = MultiIndex.from_arrays(arrays,
                                           names=['first', 'second'])
        frame.index = new_index

        new_cols_index = MultiIndex.from_tuples([(40, 1), (40, 2),
                                                 (50, 1), (50, 2)])
        frame.columns = new_cols_index
        header = [0, 1]
        if not merge_cells:
            header = 0

        # round trip
        frame.to_excel(self.path, 'test1', merge_cells=merge_cells)
        reader = ExcelFile(self.path)
        df = read_excel(reader, 'test1', header=header,
                        index_col=[0, 1])
        if not merge_cells:
            fm = frame.columns.format(sparsify=False,
                                      adjoin=False, names=False)
            frame.columns = [".".join(map(str, q)) for q in zip(*fm)]
        tm.assert_frame_equal(frame, df) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:26,代码来源:test_excel.py

示例2: construction_error

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def construction_error(tot_items, block_shape, axes, e=None):
    """ raise a helpful message about our construction """
    passed = tuple(map(int, [tot_items] + list(block_shape)))
    # Correcting the user facing error message during dataframe construction
    if len(passed) <= 2:
        passed = passed[::-1]

    implied = tuple(len(ax) for ax in axes)
    # Correcting the user facing error message during dataframe construction
    if len(implied) <= 2:
        implied = implied[::-1]

    if passed == implied and e is not None:
        raise e
    if block_shape[0] == 0:
        raise ValueError("Empty data passed with indices specified.")
    raise ValueError("Shape of passed values is {0}, indices imply {1}".format(
        passed, implied))


# ----------------------------------------------------------------------- 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:23,代码来源:managers.py

示例3: _check_ne_builtin_clash

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def _check_ne_builtin_clash(expr):
    """Attempt to prevent foot-shooting in a helpful way.

    Parameters
    ----------
    terms : Term
        Terms can contain
    """
    names = expr.names
    overlap = names & _ne_builtins

    if overlap:
        s = ', '.join(map(repr, overlap))
        raise NumExprClobberingError('Variables in expression "{expr}" '
                                     'overlap with builtins: ({s})'
                                     .format(expr=expr, s=s)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:18,代码来源:engines.py

示例4: __setitem__

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def __setitem__(self, key, value):
        key = com.apply_if_callable(key, self)
        shape = tuple(self.shape)
        if isinstance(value, self._constructor_sliced):
            value = value.reindex(
                **self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:]))
            mat = value.values
        elif isinstance(value, np.ndarray):
            if value.shape != shape[1:]:
                raise ValueError('shape of value must be {0}, shape of given '
                                 'object was {1}'.format(
                                     shape[1:], tuple(map(int, value.shape))))
            mat = np.asarray(value)
        elif is_scalar(value):
            mat = cast_scalar_to_array(shape[1:], value)
        else:
            raise TypeError('Cannot set item of '
                            'type: {dtype!s}'.format(dtype=type(value)))

        mat = mat.reshape(tuple([1]) + shape[1:])
        NDFrame._set_item(self, key, mat) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:23,代码来源:panel.py

示例5: count

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def count(self):
        """ Compute count of group, excluding missing values """
        from pandas.core.dtypes.missing import _isna_ndarraylike as _isna

        data, _ = self._get_data_to_aggregate()
        ids, _, ngroups = self.grouper.group_info
        mask = ids != -1

        val = ((mask & ~_isna(np.atleast_2d(blk.get_values())))
               for blk in data.blocks)
        loc = (blk.mgr_locs for blk in data.blocks)

        counter = partial(
            lib.count_level_2d, labels=ids, max_bin=ngroups, axis=1)
        blk = map(make_block, map(counter, val), loc)

        return self._wrap_agged_blocks(data.items, list(blk)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:19,代码来源:generic.py

示例6: applymap

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def applymap(self, func):
        """
        Apply a function to a DataFrame that is intended to operate
        elementwise, i.e. like doing map(func, series) for each series in the
        DataFrame

        Parameters
        ----------
        func : function
            Python function, returns a single value from a single value

        Returns
        -------
        applied : DataFrame
        """
        return self.apply(lambda x: lmap(func, x)) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:18,代码来源:frame.py

示例7: adjoin

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def adjoin(space, *lists):
    """
    Glues together two sets of strings using the amount of space requested.
    The idea is to prettify.
    """
    out_lines = []
    newLists = []
    lengths = [max(map(len, x)) + space for x in lists[:-1]]

    # not the last one
    lengths.append(max(map(len, lists[-1])))

    maxLen = max(map(len, lists))
    for i, lst in enumerate(lists):
        nl = [x.ljust(lengths[i]) for x in lst]
        nl.extend([' ' * lengths[i]] * (maxLen - len(lst)))
        newLists.append(nl)
    toJoin = zip(*newLists)
    for lines in toJoin:
        out_lines.append(_join_unicode(lines))
    return _join_unicode(out_lines, sep='\n') 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:23,代码来源:common.py

示例8: is_instance_factory

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def is_instance_factory(_type):
    """

    Parameters
    ----------
    `_type` - the type to be checked against

    Returns
    -------
    validator - a function of a single argument x , which returns the
                True if x is an instance of `_type`

    """
    if isinstance(_type, (tuple, list)):
        _type = tuple(_type)
        from pandas.core.common import pprint_thing
        type_repr = "|".join(map(pprint_thing, _type))
    else:
        type_repr = "'%s'" % _type

    def inner(x):
        if not isinstance(x, _type):
            raise ValueError("Value must be an instance of %s" % type_repr)

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

示例9: _reset_ref_locs

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def _reset_ref_locs(self):
        """ take the current _ref_locs and reset ref_locs on the blocks
            to correctly map, ignoring Nones;
            reset both _items_map and _ref_locs """

        # let's reset the ref_locs in individual blocks
        if self.items.is_unique:
            for b in self.blocks:
                b._ref_locs = None
        else:
            for b in self.blocks:
                b.reset_ref_locs()
        self._rebuild_ref_locs()

        self._ref_locs = None
        self._items_map = None 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:18,代码来源:internals.py

示例10: get_schema

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def get_schema(frame, name, flavor, keys=None):
    "Return a CREATE TABLE statement to suit the contents of a DataFrame."
    lookup_type = lambda dtype: get_sqltype(dtype.type, flavor)
    # Replace spaces in DataFrame column names with _.
    safe_columns = [s.replace(' ', '_').strip() for s in frame.dtypes.index]
    column_types = lzip(safe_columns, map(lookup_type, frame.dtypes))
    if flavor == 'sqlite':
        columns = ',\n  '.join('[%s] %s' % x for x in column_types)
    else:
        columns = ',\n  '.join('`%s` %s' % x for x in column_types)

    keystr = ''
    if keys is not None:
        if isinstance(keys, compat.string_types):
            keys = (keys,)
        keystr = ', PRIMARY KEY (%s)' % ','.join(keys)
    template = """CREATE TABLE %(name)s (
                  %(columns)s
                  %(keystr)s
                  );"""
    create_statement = template % {'name': name, 'columns': columns,
                                   'keystr': keystr}
    return create_statement 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:25,代码来源:sql.py

示例11: detect_colspecs

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def detect_colspecs(self, n=100):
        # Regex escape the delimiters
        delimiters = ''.join([r'\%s' % x for x in self.delimiter])
        pattern = re.compile('([^%s]+)' % delimiters)
        rows = self.get_rows(n)
        max_len = max(map(len, rows))
        mask = np.zeros(max_len + 1, dtype=int)
        if self.comment is not None:
            rows = [row.partition(self.comment)[0] for row in rows]
        for row in rows:
            for m in pattern.finditer(row):
                mask[m.start():m.end()] = 1
        shifted = np.roll(mask, 1)
        shifted[0] = 0
        edges = np.where((mask ^ shifted) == 1)[0]
        return list(zip(edges[::2], edges[1::2])) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:18,代码来源:parsers.py

示例12: legend_title

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def legend_title(self):
        if not isinstance(self.data.columns, ABCMultiIndex):
            name = self.data.columns.name
            if name is not None:
                name = pprint_thing(name)
            return name
        else:
            stringified = map(pprint_thing,
                              self.data.columns.names)
            return ','.join(stringified) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:12,代码来源:_core.py

示例13: test_string_factorize

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def test_string_factorize(self):
        # should this be optional?
        data = 'a\nb\na\nb\na'
        reader = TextReader(StringIO(data), header=None)
        result = reader.read()
        assert len(set(map(id, result[0]))) == 2 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:8,代码来源:test_textreader.py

示例14: _get_grouper_for_level

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def _get_grouper_for_level(self, mapper, level):
        indexer = self.codes[level]
        level_index = self.levels[level]

        if mapper is not None:
            # Handle group mapping function and return
            level_values = self.levels[level].take(indexer)
            grouper = level_values.map(mapper)
            return grouper, None, None

        codes, uniques = algos.factorize(indexer, sort=True)

        if len(uniques) > 0 and uniques[0] == -1:
            # Handle NAs
            mask = indexer != -1
            ok_codes, uniques = algos.factorize(indexer[mask], sort=True)

            codes = np.empty(len(indexer), dtype=indexer.dtype)
            codes[mask] = ok_codes
            codes[~mask] = -1

        if len(uniques) < len(level_index):
            # Remove unobserved levels from level_index
            level_index = level_index.take(uniques)

        grouper = level_index.take(codes)

        return grouper, codes, level_index 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:30,代码来源:multi.py

示例15: _get_multiindex_indexer

# 需要导入模块: from pandas import compat [as 别名]
# 或者: from pandas.compat import map [as 别名]
def _get_multiindex_indexer(join_keys, index, sort):
    from functools import partial

    # bind `sort` argument
    fkeys = partial(_factorize_keys, sort=sort)

    # left & right join labels and num. of levels at each location
    rcodes, lcodes, shape = map(list, zip(* map(fkeys,
                                                index.levels,
                                                join_keys)))
    if sort:
        rcodes = list(map(np.take, rcodes, index.codes))
    else:
        i8copy = lambda a: a.astype('i8', subok=False, copy=True)
        rcodes = list(map(i8copy, index.codes))

    # fix right labels if there were any nulls
    for i in range(len(join_keys)):
        mask = index.codes[i] == -1
        if mask.any():
            # check if there already was any nulls at this location
            # if there was, it is factorized to `shape[i] - 1`
            a = join_keys[i][lcodes[i] == shape[i] - 1]
            if a.size == 0 or not a[0] != a[0]:
                shape[i] += 1

            rcodes[i][mask] = shape[i] - 1

    # get flat i8 join keys
    lkey, rkey = _get_join_keys(lcodes, rcodes, shape, sort)

    # factorize keys to a dense i8 space
    lkey, rkey, count = fkeys(lkey, rkey)

    return libjoin.left_outer_join(lkey, rkey, count, sort=sort) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:37,代码来源:merge.py


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