當前位置: 首頁>>代碼示例>>Python>>正文


Python compat.OrderedDict方法代碼示例

本文整理匯總了Python中pandas.compat.OrderedDict方法的典型用法代碼示例。如果您正苦於以下問題:Python compat.OrderedDict方法的具體用法?Python compat.OrderedDict怎麽用?Python compat.OrderedDict使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pandas.compat的用法示例。


在下文中一共展示了compat.OrderedDict方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_aggregate_str_func

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_aggregate_str_func(tsframe, groupbyfunc):
    grouped = tsframe.groupby(groupbyfunc)

    # single series
    result = grouped['A'].agg('std')
    expected = grouped['A'].std()
    tm.assert_series_equal(result, expected)

    # group frame by function name
    result = grouped.aggregate('var')
    expected = grouped.var()
    tm.assert_frame_equal(result, expected)

    # group frame by function dict
    result = grouped.agg(OrderedDict([['A', 'var'],
                                      ['B', 'std'],
                                      ['C', 'mean'],
                                      ['D', 'sem']]))
    expected = DataFrame(OrderedDict([['A', grouped['A'].var()],
                                      ['B', grouped['B'].std()],
                                      ['C', grouped['C'].mean()],
                                      ['D', grouped['D'].sem()]]))
    tm.assert_frame_equal(result, expected) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:test_aggregate.py

示例2: _write_cell

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def _write_cell(self, s, kind='td', indent=0, tags=None):
        if tags is not None:
            start_tag = '<{kind} {tags}>'.format(kind=kind, tags=tags)
        else:
            start_tag = '<{kind}>'.format(kind=kind)

        if self.escape:
            # escape & first to prevent double escaping of &
            esc = OrderedDict([('&', r'&amp;'), ('<', r'&lt;'),
                               ('>', r'&gt;')])
        else:
            esc = {}

        rs = pprint_thing(s, escape_chars=esc).strip()

        if self.render_links and _is_url(rs):
            rs_unescaped = pprint_thing(s, escape_chars={}).strip()
            start_tag += '<a href="{url}" target="_blank">'.format(
                url=rs_unescaped)
            end_a = '</a>'
        else:
            end_a = ''

        self.write(u'{start}{rs}{end_a}</{kind}>'.format(
            start=start_tag, rs=rs, end_a=end_a, kind=kind), indent) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:27,代碼來源:html.py

示例3: test_ctor_orderedDict

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_ctor_orderedDict(self):
        keys = list(set(np.random.randint(0, 5000, 100)))[
            :50]  # unique random int  keys
        d = OrderedDict([(k, mkdf(10, 5)) for k in keys])
        p = Panel(d)
        assert list(p.items) == keys

        p = Panel.from_dict(d)
        assert list(p.items) == keys 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:11,代碼來源:test_panel.py

示例4: test_more_flexible_frame_multi_function

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_more_flexible_frame_multi_function(df):
    grouped = df.groupby('A')

    exmean = grouped.agg(OrderedDict([['C', np.mean], ['D', np.mean]]))
    exstd = grouped.agg(OrderedDict([['C', np.std], ['D', np.std]]))

    expected = concat([exmean, exstd], keys=['mean', 'std'], axis=1)
    expected = expected.swaplevel(0, 1, axis=1).sort_index(level=0, axis=1)

    d = OrderedDict([['C', [np.mean, np.std]], ['D', [np.mean, np.std]]])
    result = grouped.aggregate(d)

    tm.assert_frame_equal(result, expected)

    # be careful
    result = grouped.aggregate(OrderedDict([['C', np.mean],
                                            ['D', [np.mean, np.std]]]))
    expected = grouped.aggregate(OrderedDict([['C', np.mean],
                                              ['D', [np.mean, np.std]]]))
    tm.assert_frame_equal(result, expected)

    def foo(x):
        return np.mean(x)

    def bar(x):
        return np.std(x, ddof=1)

    # this uses column selection & renaming
    with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
        d = OrderedDict([['C', np.mean],
                         ['D', OrderedDict([['foo', np.mean],
                                            ['bar', np.std]])]])
        result = grouped.aggregate(d)

    d = OrderedDict([['C', [np.mean]], ['D', [foo, bar]]])
    expected = grouped.aggregate(d)

    tm.assert_frame_equal(result, expected) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:40,代碼來源:test_aggregate.py

示例5: test_multi_function_flexible_mix

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_multi_function_flexible_mix(df):
    # GH #1268
    grouped = df.groupby('A')

    # Expected
    d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])],
                     ['D', {'sum': 'sum'}]])
    # this uses column selection & renaming
    with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
        expected = grouped.aggregate(d)

    # Test 1
    d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])],
                     ['D', 'sum']])
    # this uses column selection & renaming
    with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
        result = grouped.aggregate(d)
    tm.assert_frame_equal(result, expected)

    # Test 2
    d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])],
                     ['D', ['sum']]])
    # this uses column selection & renaming
    with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
        result = grouped.aggregate(d)
    tm.assert_frame_equal(result, expected) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:28,代碼來源:test_aggregate.py

示例6: _init_dict

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def _init_dict(self, data, axes, dtype=None):
        haxis = axes.pop(self._info_axis_number)

        # prefilter if haxis passed
        if haxis is not None:
            haxis = ensure_index(haxis)
            data = OrderedDict((k, v)
                               for k, v in compat.iteritems(data)
                               if k in haxis)
        else:
            keys = com.dict_keys_to_ordered_list(data)
            haxis = Index(keys)

        for k, v in compat.iteritems(data):
            if isinstance(v, dict):
                data[k] = self._constructor_sliced(v)

        # extract axis for remaining axes & create the slicemap
        raxes = [self._extract_axis(self, data, axis=i) if a is None else a
                 for i, a in enumerate(axes)]
        raxes_sm = self._extract_axes_for_slice(self, raxes)

        # shallow copy
        arrays = []
        haxis_shape = [len(a) for a in raxes]
        for h in haxis:
            v = values = data.get(h)
            if v is None:
                values = np.empty(haxis_shape, dtype=dtype)
                values.fill(np.nan)
            elif isinstance(v, self._constructor_sliced):
                d = raxes_sm.copy()
                d['copy'] = False
                v = v.reindex(**d)
                if dtype is not None:
                    v = v.astype(dtype)
                values = v.values
            arrays.append(values)

        return self._init_arrays(arrays, haxis, [haxis] + raxes) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:42,代碼來源:panel.py

示例7: from_dict

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def from_dict(cls, data, intersect=False, orient='items', dtype=None):
        """
        Construct Panel from dict of DataFrame objects.

        Parameters
        ----------
        data : dict
            {field : DataFrame}
        intersect : boolean
            Intersect indexes of input DataFrames
        orient : {'items', 'minor'}, default 'items'
            The "orientation" of the data. If the keys of the passed dict
            should be the items of the result panel, pass 'items'
            (default). Otherwise if the columns of the values of the passed
            DataFrame objects should be the items (which in the case of
            mixed-dtype data you should do), instead pass 'minor'
        dtype : dtype, default None
            Data type to force, otherwise infer

        Returns
        -------
        Panel
        """
        from collections import defaultdict

        orient = orient.lower()
        if orient == 'minor':
            new_data = defaultdict(OrderedDict)
            for col, df in compat.iteritems(data):
                for item, s in compat.iteritems(df):
                    new_data[item][col] = s
            data = new_data
        elif orient != 'items':  # pragma: no cover
            raise ValueError('Orientation must be one of {items, minor}.')

        d = cls._homogenize_dict(cls, data, intersect=intersect, dtype=dtype)
        ks = list(d['data'].keys())
        if not isinstance(d['data'], OrderedDict):
            ks = list(sorted(ks))
        d[cls._info_axis_name] = Index(ks)
        return cls(**d) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:43,代碼來源:panel.py

示例8: dict_keys_to_ordered_list

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def dict_keys_to_ordered_list(mapping):
    # when pandas drops support for Python < 3.6, this function
    # can be replaced by a simple list(mapping.keys())
    if PY36 or isinstance(mapping, OrderedDict):
        keys = list(mapping.keys())
    else:
        keys = try_sort(mapping)
    return keys 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:10,代碼來源:common.py

示例9: test_ctor_orderedDict

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_ctor_orderedDict(self):
        with catch_warnings(record=True):
            keys = list(set(np.random.randint(0, 5000, 100)))[
                :50]  # unique random int  keys
            d = OrderedDict([(k, mkdf(10, 5)) for k in keys])
            p = Panel(d)
            assert list(p.items) == keys

            p = Panel.from_dict(d)
            assert list(p.items) == keys 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:12,代碼來源:test_panel.py

示例10: _dict_keys_to_ordered_list

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def _dict_keys_to_ordered_list(mapping):
    # when pandas drops support for Python < 3.6, this function
    # can be replaced by a simple list(mapping.keys())
    if PY36 or isinstance(mapping, OrderedDict):
        keys = list(mapping.keys())
    else:
        keys = _try_sort(mapping)
    return keys 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:10,代碼來源:common.py

示例11: _to_recarray

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def _to_recarray(self, data, columns):
        dtypes = []
        o = compat.OrderedDict()

        # use the columns to "order" the keys
        # in the unordered 'data' dictionary
        for col in columns:
            dtypes.append((str(col), data[col].dtype))
            o[col] = data[col]

        tuples = lzip(*o.values())
        return np.array(tuples, dtypes) 
開發者ID:nccgroup,項目名稱:Splunking-Crime,代碼行數:14,代碼來源:parsers.py

示例12: test_aggregate_str_func

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_aggregate_str_func(self):
        def _check_results(grouped):
            # single series
            result = grouped['A'].agg('std')
            expected = grouped['A'].std()
            assert_series_equal(result, expected)

            # group frame by function name
            result = grouped.aggregate('var')
            expected = grouped.var()
            assert_frame_equal(result, expected)

            # group frame by function dict
            result = grouped.agg(OrderedDict([['A', 'var'], ['B', 'std'],
                                              ['C', 'mean'], ['D', 'sem']]))
            expected = DataFrame(OrderedDict([['A', grouped['A'].var(
            )], ['B', grouped['B'].std()], ['C', grouped['C'].mean()],
                ['D', grouped['D'].sem()]]))
            assert_frame_equal(result, expected)

        by_weekday = self.tsframe.groupby(lambda x: x.weekday())
        _check_results(by_weekday)

        by_mwkday = self.tsframe.groupby([lambda x: x.month,
                                          lambda x: x.weekday()])
        _check_results(by_mwkday) 
開發者ID:securityclippy,項目名稱:elasticintel,代碼行數:28,代碼來源:test_aggregate.py

示例13: test_more_flexible_frame_multi_function

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_more_flexible_frame_multi_function(self):

        grouped = self.df.groupby('A')

        exmean = grouped.agg(OrderedDict([['C', np.mean], ['D', np.mean]]))
        exstd = grouped.agg(OrderedDict([['C', np.std], ['D', np.std]]))

        expected = concat([exmean, exstd], keys=['mean', 'std'], axis=1)
        expected = expected.swaplevel(0, 1, axis=1).sort_index(level=0, axis=1)

        d = OrderedDict([['C', [np.mean, np.std]], ['D', [np.mean, np.std]]])
        result = grouped.aggregate(d)

        assert_frame_equal(result, expected)

        # be careful
        result = grouped.aggregate(OrderedDict([['C', np.mean],
                                                ['D', [np.mean, np.std]]]))
        expected = grouped.aggregate(OrderedDict([['C', np.mean],
                                                  ['D', [np.mean, np.std]]]))
        assert_frame_equal(result, expected)

        def foo(x):
            return np.mean(x)

        def bar(x):
            return np.std(x, ddof=1)

        # this uses column selection & renaming
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            d = OrderedDict([['C', np.mean], ['D', OrderedDict(
                [['foo', np.mean], ['bar', np.std]])]])
            result = grouped.aggregate(d)

        d = OrderedDict([['C', [np.mean]], ['D', [foo, bar]]])
        expected = grouped.aggregate(d)

        assert_frame_equal(result, expected) 
開發者ID:securityclippy,項目名稱:elasticintel,代碼行數:41,代碼來源:test_aggregate.py

示例14: test_multi_function_flexible_mix

# 需要導入模塊: from pandas import compat [as 別名]
# 或者: from pandas.compat import OrderedDict [as 別名]
def test_multi_function_flexible_mix(self):
        # GH #1268
        grouped = self.df.groupby('A')

        d = OrderedDict([['C', OrderedDict([['foo', 'mean'], [
            'bar', 'std'
        ]])], ['D', 'sum']])

        # this uses column selection & renaming
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            result = grouped.aggregate(d)

        d2 = OrderedDict([['C', OrderedDict([['foo', 'mean'], [
            'bar', 'std'
        ]])], ['D', ['sum']]])

        # this uses column selection & renaming
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            result2 = grouped.aggregate(d2)

        d3 = OrderedDict([['C', OrderedDict([['foo', 'mean'], [
            'bar', 'std'
        ]])], ['D', {'sum': 'sum'}]])

        # this uses column selection & renaming
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            expected = grouped.aggregate(d3)

        assert_frame_equal(result, expected)
        assert_frame_equal(result2, expected) 
開發者ID:securityclippy,項目名稱:elasticintel,代碼行數:35,代碼來源:test_aggregate.py


注:本文中的pandas.compat.OrderedDict方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。