Python pandas.io.formats.printing.pprint_thing() Examples

The following are 30 code examples of pandas.io.formats.printing.pprint_thing(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pandas.io.formats.printing , or try the search function .
Example #1
Source File: test_format.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_pprint_thing(self):
        from pandas.io.formats.printing import pprint_thing as pp_t

        if PY3:
            pytest.skip("doesn't work on Python 3")

        assert pp_t('a') == u('a')
        assert pp_t(u('a')) == u('a')
        assert pp_t(None) == 'None'
        assert pp_t(u('\u05d0'), quote_strings=True) == u("u'\u05d0'")
        assert pp_t(u('\u05d0'), quote_strings=False) == u('\u05d0')
        assert (pp_t((u('\u05d0'), u('\u05d1')), quote_strings=True) ==
                u("(u'\u05d0', u'\u05d1')"))
        assert (pp_t((u('\u05d0'), (u('\u05d1'), u('\u05d2'))),
                     quote_strings=True) == u("(u'\u05d0', "
                                              "(u'\u05d1', u'\u05d2'))"))
        assert (pp_t(('foo', u('\u05d0'), (u('\u05d0'), u('\u05d0'))),
                     quote_strings=True) == u("(u'foo', u'\u05d0', "
                                              "(u'\u05d0', u'\u05d0'))"))

        # gh-2038: escape embedded tabs in string
        assert "\t" not in pp_t("a\tb", escape_chars=("\t", )) 
Example #2
Source File: test_format.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_pprint_thing(self):
        from pandas.io.formats.printing import pprint_thing as pp_t

        if PY3:
            pytest.skip("doesn't work on Python 3")

        assert pp_t('a') == u('a')
        assert pp_t(u('a')) == u('a')
        assert pp_t(None) == 'None'
        assert pp_t(u('\u05d0'), quote_strings=True) == u("u'\u05d0'")
        assert pp_t(u('\u05d0'), quote_strings=False) == u('\u05d0')
        assert (pp_t((u('\u05d0'), u('\u05d1')), quote_strings=True) ==
                u("(u'\u05d0', u'\u05d1')"))
        assert (pp_t((u('\u05d0'), (u('\u05d1'), u('\u05d2'))),
                     quote_strings=True) == u("(u'\u05d0', "
                                              "(u'\u05d1', u'\u05d2'))"))
        assert (pp_t(('foo', u('\u05d0'), (u('\u05d0'), u('\u05d0'))),
                     quote_strings=True) == u("(u'foo', u'\u05d0', "
                                              "(u'\u05d0', u'\u05d0'))"))

        # gh-2038: escape embedded tabs in string
        assert "\t" not in pp_t("a\tb", escape_chars=("\t", )) 
Example #3
Source File: _core.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _make_plot(self):
        colors = self._get_colors()
        stacking_id = self._get_stacking_id()

        for i, (label, y) in enumerate(self._iter_data()):
            ax = self._get_ax(i)

            kwds = self.kwds.copy()

            label = pprint_thing(label)
            kwds['label'] = label

            style, kwds = self._apply_style_colors(colors, kwds, i, label)
            if style is not None:
                kwds['style'] = style

            kwds = self._make_plot_keywords(kwds, y)
            artists = self._plot(ax, y, column_num=i,
                                 stacking_id=stacking_id, **kwds)
            self._add_legend_handle(artists[0], label, index=i) 
Example #4
Source File: blocks.py    From recruit with Apache License 2.0 6 votes vote down vote up
def __unicode__(self):

        # don't want to print out all of the items here
        name = pprint_thing(self.__class__.__name__)
        if self._is_single_block:

            result = '{name}: {len} dtype: {dtype}'.format(
                name=name, len=len(self), dtype=self.dtype)

        else:

            shape = ' x '.join(pprint_thing(s) for s in self.shape)
            result = '{name}: {index}, {shape}, dtype: {dtype}'.format(
                name=name, index=pprint_thing(self.mgr_locs.indexer),
                shape=shape, dtype=self.dtype)

        return result 
Example #5
Source File: common.py    From recruit with Apache License 2.0 6 votes vote down vote up
def writerows(self, rows):
            def _check_as_is(x):
                return (self.quoting == csv.QUOTE_NONNUMERIC and
                        is_number(x)) or isinstance(x, str)

            for i, row in enumerate(rows):
                rows[i] = [x if _check_as_is(x)
                           else pprint_thing(x).encode("utf-8") for x in row]

            self.writer.writerows([[s for s in row] for row in rows])
            # Fetch UTF-8 output from the queue ...
            data = self.queue.getvalue()
            data = data.decode("utf-8")
            # ... and re-encode it into the target encoding
            data = self.encoder.encode(data)
            # write to the target stream
            self.stream.write(data)
            # empty queue
            self.queue.truncate(0) 
Example #6
Source File: common.py    From recruit with Apache License 2.0 6 votes vote down vote up
def writerow(self, row):
            def _check_as_is(x):
                return (self.quoting == csv.QUOTE_NONNUMERIC and
                        is_number(x)) or isinstance(x, str)

            row = [x if _check_as_is(x)
                   else pprint_thing(x).encode("utf-8") for x in row]

            self.writer.writerow([s for s in row])
            # Fetch UTF-8 output from the queue ...
            data = self.queue.getvalue()
            data = data.decode("utf-8")
            # ... and re-encode it into the target encoding
            data = self.encoder.encode(data)
            # write to the target stream
            self.stream.write(data)
            # empty queue
            self.queue.truncate(0) 
Example #7
Source File: _core.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _make_plot(self):
        colors = self._get_colors()
        stacking_id = self._get_stacking_id()

        for i, (label, y) in enumerate(self._iter_data()):
            ax = self._get_ax(i)

            kwds = self.kwds.copy()

            label = pprint_thing(label)
            kwds['label'] = label

            style, kwds = self._apply_style_colors(colors, kwds, i, label)
            if style is not None:
                kwds['style'] = style

            kwds = self._make_plot_keywords(kwds, y)
            artists = self._plot(ax, y, column_num=i,
                                 stacking_id=stacking_id, **kwds)
            self._add_legend_handle(artists[0], label, index=i) 
Example #8
Source File: html.py    From recruit with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: config.py    From recruit with Apache License 2.0 6 votes vote down vote up
def is_one_of_factory(legal_values):

    callables = [c for c in legal_values if callable(c)]
    legal_values = [c for c in legal_values if not callable(c)]

    def inner(x):
        from pandas.io.formats.printing import pprint_thing as pp
        if x not in legal_values:

            if not any(c(x) for c in callables):
                pp_values = pp("|".join(lmap(pp, legal_values)))
                msg = "Value must be one of {pp_values}"
                if len(callables):
                    msg += " or a callable"
                raise ValueError(msg.format(pp_values=pp_values))

    return inner


# common type validators, for convenience
# usage: register_option(... , validator = is_int) 
Example #10
Source File: frozen.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __unicode__(self):
        return pprint_thing(self, quote_strings=True,
                            escape_chars=('\t', '\r', '\n')) 
Example #11
Source File: datetimelike.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _summary(self, name=None):
        """
        Return a summarized representation

        Parameters
        ----------
        name : str
            name to use in the summary representation

        Returns
        -------
        String with a summarized representation of the index
        """
        formatter = self._formatter_func
        if len(self) > 0:
            index_summary = ', %s to %s' % (formatter(self[0]),
                                            formatter(self[-1]))
        else:
            index_summary = ''

        if name is None:
            name = type(self).__name__
        result = '%s: %s entries%s' % (printing.pprint_thing(name),
                                       len(self), index_summary)
        if self.freq:
            result += '\nFreq: %s' % self.freqstr

        # display as values, not quoted
        result = result.replace("'", "")
        return result 
Example #12
Source File: base.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def format(self, name=False, formatter=None, **kwargs):
        """
        Render a string representation of the Index
        """
        header = []
        if name:
            header.append(pprint_thing(self.name,
                                       escape_chars=('\t', '\r', '\n')) if
                          self.name is not None else '')

        if formatter is not None:
            return header + list(self.map(formatter))

        return self._format_with_header(header, **kwargs) 
Example #13
Source File: array.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __unicode__(self):
        return '{self}\nFill: {fill}\n{index}'.format(
            self=printing.pprint_thing(self),
            fill=printing.pprint_thing(self.fill_value),
            index=printing.pprint_thing(self.sp_index)) 
Example #14
Source File: _core.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _post_plot_logic_common(self, ax, data):
        """Common post process for each axes"""

        def get_label(i):
            try:
                return pprint_thing(data.index[i])
            except Exception:
                return ''

        if self.orientation == 'vertical' or self.orientation is None:
            if self._need_to_set_index:
                xticklabels = [get_label(x) for x in ax.get_xticks()]
                ax.set_xticklabels(xticklabels)
            self._apply_axis_properties(ax.xaxis, rot=self.rot,
                                        fontsize=self.fontsize)
            self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)

            if hasattr(ax, 'right_ax'):
                self._apply_axis_properties(ax.right_ax.yaxis,
                                            fontsize=self.fontsize)

        elif self.orientation == 'horizontal':
            if self._need_to_set_index:
                yticklabels = [get_label(y) for y in ax.get_yticks()]
                ax.set_yticklabels(yticklabels)
            self._apply_axis_properties(ax.yaxis, rot=self.rot,
                                        fontsize=self.fontsize)
            self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)

            if hasattr(ax, 'right_ax'):
                self._apply_axis_properties(ax.right_ax.yaxis,
                                            fontsize=self.fontsize)
        else:  # pragma no cover
            raise ValueError 
Example #15
Source File: test_api.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_copy_index_name_checking(self):
        # don't want to be able to modify the index stored elsewhere after
        # making a copy

        self.ts.index.name = None
        assert self.ts.index.name is None
        assert self.ts is self.ts

        cp = self.ts.copy()
        cp.index.name = 'foo'
        printing.pprint_thing(self.ts.index.name)
        assert self.ts.index.name is None 
Example #16
Source File: testing.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def raise_assert_detail(obj, message, left, right, diff=None):
    if isinstance(left, np.ndarray):
        left = pprint_thing(left)
    elif is_categorical_dtype(left):
        left = repr(left)

    if PY2 and isinstance(left, string_types):
        # left needs to be printable in native text type in python2
        left = left.encode('utf-8')

    if isinstance(right, np.ndarray):
        right = pprint_thing(right)
    elif is_categorical_dtype(right):
        right = repr(right)

    if PY2 and isinstance(right, string_types):
        # right needs to be printable in native text type in python2
        right = right.encode('utf-8')

    msg = """{obj} are different

{message}
[left]:  {left}
[right]: {right}""".format(obj=obj, message=message, left=left, right=right)

    if diff is not None:
        msg += "\n[diff]: {diff}".format(diff=diff)

    raise AssertionError(msg) 
Example #17
Source File: base.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _summary(self, name=None):
        """
        Return a summarized representation

        Parameters
        ----------
        name : str
            name to use in the summary representation

        Returns
        -------
        String with a summarized representation of the index
        """
        if len(self) > 0:
            head = self[0]
            if (hasattr(head, 'format') and
                    not isinstance(head, compat.string_types)):
                head = head.format()
            tail = self[-1]
            if (hasattr(tail, 'format') and
                    not isinstance(tail, compat.string_types)):
                tail = tail.format()
            index_summary = ', %s to %s' % (pprint_thing(head),
                                            pprint_thing(tail))
        else:
            index_summary = ''

        if name is None:
            name = type(self).__name__
        return '%s: %s entries%s' % (name, len(self), index_summary) 
Example #18
Source File: _core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _make_plot(self):
        if self.subplots:
            from pandas.core.series import Series
            self._return_obj = Series()

            for i, (label, y) in enumerate(self._iter_data()):
                ax = self._get_ax(i)
                kwds = self.kwds.copy()

                ret, bp = self._plot(ax, y, column_num=i,
                                     return_type=self.return_type, **kwds)
                self.maybe_color_bp(bp)
                self._return_obj[label] = ret

                label = [pprint_thing(label)]
                self._set_ticklabels(ax, label)
        else:
            y = self.data.values.T
            ax = self._get_ax(0)
            kwds = self.kwds.copy()

            ret, bp = self._plot(ax, y, column_num=0,
                                 return_type=self.return_type, **kwds)
            self.maybe_color_bp(bp)
            self._return_obj = ret

            labels = [l for l, _ in self._iter_data()]
            labels = [pprint_thing(l) for l in labels]
            if not self.use_index:
                labels = [pprint_thing(key) for key in range(len(labels))]
            self._set_ticklabels(ax, labels) 
Example #19
Source File: _core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _post_plot_logic(self, ax, data):
        if self.use_index:
            str_index = [pprint_thing(key) for key in data.index]
        else:
            str_index = [pprint_thing(key) for key in range(data.shape[0])]
        name = self._get_index_name()

        s_edge = self.ax_pos[0] - 0.25 + self.lim_offset
        e_edge = self.ax_pos[-1] + 0.25 + self.bar_width + self.lim_offset

        self._decorate_ticks(ax, name, str_index, s_edge, e_edge) 
Example #20
Source File: _core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _make_plot(self):
        if self._is_ts_plot():
            from pandas.plotting._timeseries import _maybe_convert_index
            data = _maybe_convert_index(self._get_ax(0), self.data)

            x = data.index      # dummy, not used
            plotf = self._ts_plot
            it = self._iter_data(data=data, keep_index=True)
        else:
            x = self._get_xticks(convert_period=True)
            plotf = self._plot
            it = self._iter_data()

        stacking_id = self._get_stacking_id()
        is_errorbar = com._any_not_none(*self.errors.values())

        colors = self._get_colors()
        for i, (label, y) in enumerate(it):
            ax = self._get_ax(i)
            kwds = self.kwds.copy()
            style, kwds = self._apply_style_colors(colors, kwds, i, label)

            errors = self._get_errorbars(label=label, index=i)
            kwds = dict(kwds, **errors)

            label = pprint_thing(label)  # .encode('utf-8')
            kwds['label'] = label

            newlines = plotf(ax, x, y, style=style, column_num=i,
                             stacking_id=stacking_id,
                             is_errorbar=is_errorbar,
                             **kwds)
            self._add_legend_handle(newlines[0], label, index=i)

            if not _mpl_ge_2_0_0():
                lines = _get_all_lines(ax)
                left, right = _get_xlim(lines)
                ax.set_xlim(left, right) 
Example #21
Source File: _core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _post_plot_logic(self, ax, data):
        x, y = self.x, self.y
        ax.set_ylabel(pprint_thing(y))
        ax.set_xlabel(pprint_thing(x)) 
Example #22
Source File: _core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _get_index_name(self):
        if isinstance(self.data.index, MultiIndex):
            name = self.data.index.names
            if com._any_not_none(*name):
                name = ','.join(pprint_thing(x) for x in name)
            else:
                name = None
        else:
            name = self.data.index.name
            if name is not None:
                name = pprint_thing(name)

        return name 
Example #23
Source File: _core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def legend_title(self):
        if not isinstance(self.data.columns, MultiIndex):
            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) 
Example #24
Source File: _core.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _post_plot_logic_common(self, ax, data):
        """Common post process for each axes"""

        def get_label(i):
            try:
                return pprint_thing(data.index[i])
            except Exception:
                return ''

        if self.orientation == 'vertical' or self.orientation is None:
            if self._need_to_set_index:
                xticklabels = [get_label(x) for x in ax.get_xticks()]
                ax.set_xticklabels(xticklabels)
            self._apply_axis_properties(ax.xaxis, rot=self.rot,
                                        fontsize=self.fontsize)
            self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)

            if hasattr(ax, 'right_ax'):
                self._apply_axis_properties(ax.right_ax.yaxis,
                                            fontsize=self.fontsize)

        elif self.orientation == 'horizontal':
            if self._need_to_set_index:
                yticklabels = [get_label(y) for y in ax.get_yticks()]
                ax.set_yticklabels(yticklabels)
            self._apply_axis_properties(ax.yaxis, rot=self.rot,
                                        fontsize=self.fontsize)
            self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)

            if hasattr(ax, 'right_ax'):
                self._apply_axis_properties(ax.right_ax.yaxis,
                                            fontsize=self.fontsize)
        else:  # pragma no cover
            raise ValueError 
Example #25
Source File: json.py    From recruit with Apache License 2.0 5 votes vote down vote up
def check_keys_split(self, decoded):
        """
        Checks that dict has only the appropriate keys for orient='split'.
        """
        bad_keys = set(decoded.keys()).difference(set(self._split_keys))
        if bad_keys:
            bad_keys = ", ".join(bad_keys)
            raise ValueError(u("JSON data had unexpected key(s): {bad_keys}")
                             .format(bad_keys=pprint_thing(bad_keys))) 
Example #26
Source File: pytables.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __unicode__(self):
        """ return a pretty representation of myself """
        self.infer_axes()
        s = self.shape
        if s is not None:
            if isinstance(s, (list, tuple)):
                s = "[{shape}]".format(
                    shape=','.join(pprint_thing(x) for x in s))
            return "{type:12.12} (shape->{shape})".format(
                type=self.pandas_type, shape=s)
        return self.pandas_type 
Example #27
Source File: pytables.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __unicode__(self):
        temp = tuple(
            map(pprint_thing,
                    (self.name,
                     self.cname,
                     self.dtype,
                     self.kind,
                     self.shape)))
        return ','.join(("{key}->{value}".format(key=key, value=value)
                         for key, value in zip(
            ['name', 'cname', 'dtype', 'kind', 'shape'], temp))) 
Example #28
Source File: pytables.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __unicode__(self):
        temp = tuple(
            map(pprint_thing,
                    (self.name,
                     self.cname,
                     self.axis,
                     self.pos,
                     self.kind)))
        return ','.join(("{key}->{value}".format(key=key, value=value)
                         for key, value in zip(
            ['name', 'cname', 'axis', 'pos', 'kind'], temp))) 
Example #29
Source File: pytables.py    From recruit with Apache License 2.0 5 votes vote down vote up
def info(self):
        """
        Print detailed information on the store.

        .. versionadded:: 0.21.0
        """
        output = '{type}\nFile path: {path}\n'.format(
            type=type(self), path=pprint_thing(self._path))
        if self.is_open:
            lkeys = sorted(list(self.keys()))
            if len(lkeys):
                keys = []
                values = []

                for k in lkeys:
                    try:
                        s = self.get_storer(k)
                        if s is not None:
                            keys.append(pprint_thing(s.pathname or k))
                            values.append(
                                pprint_thing(s or 'invalid_HDFStore node'))
                    except Exception as detail:
                        keys.append(k)
                        values.append(
                            "[invalid_HDFStore node: {detail}]".format(
                                detail=pprint_thing(detail)))

                output += adjoin(12, keys, values)
            else:
                output += 'Empty'
        else:
            output += "File is CLOSED"

        return output

    # private methods ###### 
Example #30
Source File: format.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _get_footer(self):
        name = self.series.name
        footer = u('')

        if getattr(self.series.index, 'freq', None) is not None:
            footer += 'Freq: {freq}'.format(freq=self.series.index.freqstr)

        if self.name is not False and name is not None:
            if footer:
                footer += ', '

            series_name = pprint_thing(name,
                                       escape_chars=('\t', '\r', '\n'))
            footer += ((u"Name: {sname}".format(sname=series_name))
                       if name is not None else "")

        if (self.length is True or
                (self.length == 'truncate' and self.truncate_v)):
            if footer:
                footer += ', '
            footer += 'Length: {length}'.format(length=len(self.series))

        if self.dtype is not False and self.dtype is not None:
            name = getattr(self.tr_series.dtype, 'name', None)
            if name:
                if footer:
                    footer += ', '
                footer += u'dtype: {typ}'.format(typ=pprint_thing(name))

        # level infos are added to the end and in a new line, like it is done
        # for Categoricals
        if is_categorical_dtype(self.tr_series.dtype):
            level_info = self.tr_series._values._repr_categories_info()
            if footer:
                footer += "\n"
            footer += level_info

        return compat.text_type(footer)