def __unicode__(self): """ Return a string representation for a particular Panel Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. """ class_name = str(self.__class__) I, N, K = len(self.items), len(self.major_axis), len(self.minor_axis) dims = u'Dimensions: %d (items) x %d (major) x %d (minor)' % (I, N, K) if len(self.major_axis) > 0: major = u'Major axis: %s to %s' % (self.major_axis[0], self.major_axis[-1]) else: major = u'Major axis: None' if len(self.minor_axis) > 0: minor = u'Minor axis: %s to %s' % (com.pprint_thing( self.minor_axis[0]), com.pprint_thing(self.minor_axis[-1])) else: minor = u'Minor axis: None' if len(self.items) > 0: items = u'Items: %s to %s' % (com.pprint_thing( self.items[0]), com.pprint_thing(self.items[-1])) else: items = u'Items: None' output = u'%s\n%s\n%s\n%s\n%s' % (class_name, dims, items, major, minor) return output
def __repr__(self): shape = " x ".join([com.pprint_thing(s) for s in self.shape]) name = type(self).__name__ result = "%s: %s, %s, dtype %s" % (name, com.pprint_thing(self.items), shape, self.dtype) if py3compat.PY3: return unicode(result) return com.console_encode(result)
def to_string(self, force_unicode=None): """ Render a DataFrame to a console-friendly tabular output. """ import warnings if force_unicode is not None: # pragma: no cover warnings.warn( "force_unicode is deprecated, it will have no effect", FutureWarning) frame = self.frame if len(frame.columns) == 0 or len(frame.index) == 0: info_line = ( u'Empty %s\nColumns: %s\nIndex: %s' % (type(self.frame).__name__, com.pprint_thing( frame.columns), com.pprint_thing(frame.index))) text = info_line else: strcols = self._to_str_columns() if self.line_width is None: text = adjoin(1, *strcols) else: text = self._join_multiline(*strcols) self.buf.writelines(text)
def _get_footer(self): footer = u'' if self.name: if getattr(self.series.index, 'freq', None): footer += 'Freq: %s' % self.series.index.freqstr if footer and self.series.name is not None: footer += ', ' series_name = com.pprint_thing(self.series.name, escape_chars=('\t', '\r', '\n')) footer += ("Name: %s" % series_name) if self.series.name is not None else "" if self.length: if footer: footer += ', ' footer += 'Length: %d' % len(self.series) if self.dtype: if getattr(self.series.dtype,'name',None): if footer: footer += ', ' footer += 'Dtype: %s' % com.pprint_thing(self.series.dtype.name) return unicode(footer)
def __unicode__(self): """Print a generic n-ary operator and its operands using infix notation""" # recurse over the operands parened = ('({0})'.format(com.pprint_thing(opr)) for opr in self.operands) return com.pprint_thing(' {0} '.format(self.op).join(parened))
def run_arithmetic_test(self, df, other, assert_func, check_dtype=False, test_flex=True): expr._MIN_ELEMENTS = 0 operations = ['add', 'sub', 'mul', 'mod', 'truediv', 'floordiv', 'pow'] if not compat.PY3: operations.append('div') for arith in operations: operator_name = arith if arith == 'div': operator_name = 'truediv' if test_flex: op = lambda x, y: getattr(df, arith)(y) op.__name__ = arith else: op = getattr(operator, operator_name) expr.set_use_numexpr(False) expected = op(df, other) expr.set_use_numexpr(True) result = op(df, other) try: if check_dtype: if arith == 'truediv': assert expected.dtype.kind == 'f' assert_func(expected, result) except Exception: com.pprint_thing("Failed test with operator %r" % op.__name__) raise
def run_binary_test(self, df, other, assert_func, test_flex=False, numexpr_ops=set(['gt', 'lt', 'ge', 'le', 'eq', 'ne'])): """ tests solely that the result is the same whether or not numexpr is enabled. Need to test whether the function does the correct thing elsewhere. """ expr._MIN_ELEMENTS = 0 expr.set_test_mode(True) operations = ['gt', 'lt', 'ge', 'le', 'eq', 'ne'] for arith in operations: if test_flex: op = lambda x, y: getattr(df, arith)(y) op.__name__ = arith else: op = getattr(operator, arith) expr.set_use_numexpr(False) expected = op(df, other) expr.set_use_numexpr(True) expr.get_test_result() result = op(df, other) used_numexpr = expr.get_test_result() try: if arith in numexpr_ops: assert used_numexpr, "Did not use numexpr as expected." else: assert not used_numexpr, "Used numexpr unexpectedly." assert_func(expected, result) except Exception: com.pprint_thing("Failed test with operation %r" % arith) com.pprint_thing("test_flex was %r" % test_flex) raise
def to_string(self, force_unicode=None): """ Render a DataFrame to a console-friendly tabular output. """ import warnings if force_unicode is not None: # pragma: no cover warnings.warn("force_unicode is deprecated, it will have no effect", FutureWarning) frame = self.frame if len(frame.columns) == 0 or len(frame.index) == 0: info_line = (u'Empty %s\nColumns: %s\nIndex: %s' % (type(self.frame).__name__, com.pprint_thing(frame.columns), com.pprint_thing(frame.index))) text = info_line else: strcols = self._to_str_columns() if self.line_width is None: text = adjoin(1, *strcols) else: text = self._join_multiline(*strcols) self.buf.writelines(text)
def __unicode__(self): """ Return a string representation for a particular Panel Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. """ class_name = str(self.__class__) I, N, K = len(self.items), len(self.major_axis), len(self.minor_axis) dims = u'Dimensions: %d (items) x %d (major) x %d (minor)' % (I, N, K) if len(self.major_axis) > 0: major = u'Major axis: %s to %s' % (self.major_axis[0], self.major_axis[-1]) else: major = u'Major axis: None' if len(self.minor_axis) > 0: minor = u'Minor axis: %s to %s' % (com.pprint_thing(self.minor_axis[0]), com.pprint_thing(self.minor_axis[-1])) else: minor = u'Minor axis: None' if len(self.items) > 0: items = u'Items: %s to %s' % (com.pprint_thing(self.items[0]), com.pprint_thing(self.items[-1])) else: items = u'Items: None' output = u'%s\n%s\n%s\n%s\n%s' % (class_name, dims, items, major, minor) return output
def __repr__(self): shape = ' x '.join([com.pprint_thing(s) for s in self.shape]) name = type(self).__name__ result = '%s: %s, %s, dtype %s' % (name, com.pprint_thing( self.items), shape, self.dtype) if py3compat.PY3: return unicode(result) return com.console_encode(result)
def axis_pretty(a): v = getattr(self, a) if len(v) > 0: return u('%s axis: %s to %s') % (a.capitalize(), com.pprint_thing(v[0]), com.pprint_thing(v[-1])) else: return u('%s axis: None') % a.capitalize()
def test_repr_obeys_max_seq_limit(self): import pandas.core.common as com # unlimited reset_option("display.max_seq_items") self.assertTrue(len(com.pprint_thing(range(1000))) > 2000) with option_context("display.max_seq_items", 5): self.assertTrue(len(com.pprint_thing(range(1000))) < 100)
def check_extension(cls, ext): """checks that path's extension against the Writer's supported extensions. If it isn't supported, raises UnsupportedFiletypeError.""" if ext.startswith('.'): ext = ext[1:] if not any(ext in extension for extension in cls.supported_extensions): msg = (u("Invalid extension for engine '%s': '%s'") % (pprint_thing(cls.engine), pprint_thing(ext))) raise ValueError(msg) else: return True
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 self.assertIsNone(self.ts.index.name) self.assertIs(self.ts, self.ts) cp = self.ts.copy() cp.index.name = 'foo' com.pprint_thing(self.ts.index.name) self.assertIsNone(self.ts.index.name)
def summary(self, name=None): if len(self) > 0: index_summary = ", %s to %s" % (com.pprint_thing(self[0]), com.pprint_thing(self[-1])) else: index_summary = "" if name is None: name = type(self).__name__ result = "%s: %s entries%s" % (com.pprint_thing(name), len(self), index_summary) if self.freq: result += "\nFreq: %s" % self.freqstr return result
def test_repr_binary_type(): import string letters = string.ascii_letters btype = compat.binary_type try: raw = btype(letters, encoding=cf.get_option('display.encoding')) except TypeError: raw = btype(letters) b = compat.text_type(compat.bytes_to_str(raw)) res = com.pprint_thing(b, quote_strings=True) assert_equal(res, repr(b)) res = com.pprint_thing(b, quote_strings=False) assert_equal(res, b)
def summary(self, name=None): if len(self) > 0: index_summary = ', %s to %s' % (com.pprint_thing( self[0]), com.pprint_thing(self[-1])) else: index_summary = '' if name is None: name = type(self).__name__ result = '%s: %s entries%s' % (com.pprint_thing(name), len(self), index_summary) if self.freq: result += '\nFreq: %s' % self.freqstr return result
def _convert_expression(expr): """Convert an object to an expression. Thus function converts an object to an expression (a unicode string) and checks to make sure it isn't empty after conversion. This is used to convert operators to their string representation for recursive calls to :func:`~pandas.eval`. Parameters ---------- expr : object The object to be converted to a string. Returns ------- s : unicode The string representation of an object. Raises ------ ValueError * If the expression is empty. """ s = com.pprint_thing(expr) _check_expression(s) return s
def _replot_ax(ax, freq, kwargs): data = getattr(ax, '_plot_data', None) # clear current axes and data ax._plot_data = [] ax.clear() _decorate_axes(ax, freq, kwargs) lines = [] labels = [] if data is not None: for series, plotf, kwds in data: series = series.copy() idx = series.index.asfreq(freq, how='S') series.index = idx ax._plot_data.append((series, plotf, kwds)) # for tsplot if isinstance(plotf, compat.string_types): from pandas.tools.plotting import _plot_klass plotf = _plot_klass[plotf]._plot lines.append(plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0]) labels.append(com.pprint_thing(series.name)) return lines, labels
def _convert_to_array(self, values, name=None, other=None): """converts values to ndarray""" from pandas.tseries.timedeltas import to_timedelta coerce = True if not is_list_like(values): values = np.array([values]) inferred_type = lib.infer_dtype(values) if inferred_type in ('datetime64', 'datetime', 'date', 'time'): # if we have a other of timedelta, but use pd.NaT here we # we are in the wrong path if (other is not None and other.dtype == 'timedelta64[ns]' and all(isnull(v) for v in values)): values = np.empty(values.shape, dtype=other.dtype) values[:] = iNaT # a datelike elif isinstance(values, pd.DatetimeIndex): values = values.to_series() elif not (isinstance(values, (np.ndarray, pd.Series)) and is_datetime64_dtype(values)): values = tslib.array_to_datetime(values) elif inferred_type in ('timedelta', 'timedelta64'): # have a timedelta, convert to to ns here values = to_timedelta(values, coerce=coerce) elif inferred_type == 'integer': # py3 compat where dtype is 'm' but is an integer if values.dtype.kind == 'm': values = values.astype('timedelta64[ns]') elif isinstance(values, pd.PeriodIndex): values = values.to_timestamp().to_series() elif name not in ('__truediv__', '__div__', '__mul__'): raise TypeError("incompatible type for a datetime/timedelta " "operation [{0}]".format(name)) elif isinstance(values[0], pd.DateOffset): # handle DateOffsets os = np.array([getattr(v, 'delta', None) for v in values]) mask = isnull(os) if mask.any(): raise TypeError("cannot use a non-absolute DateOffset in " "datetime/timedelta operations [{0}]".format( ', '.join([com.pprint_thing(v) for v in values[mask]]))) values = to_timedelta(os, coerce=coerce) elif inferred_type == 'floating': # all nan, so ok, use the other dtype (e.g. timedelta or datetime) if isnull(values).all(): values = np.empty(values.shape, dtype=other.dtype) values[:] = iNaT else: raise TypeError( 'incompatible type [{0}] for a datetime/timedelta ' 'operation'.format(np.array(values).dtype)) else: raise TypeError("incompatible type [{0}] for a datetime/timedelta" " operation".format(np.array(values).dtype)) return values
def _write_cell(self, s, kind='td', indent=0, tags=None): if tags is not None: start_tag = '<%s %s>' % (kind, tags) else: start_tag = '<%s>' % kind self.write('%s%s</%s>' % (start_tag, com.pprint_thing(s), kind), indent)
def _write_cell(self, s, kind='td', indent=0, tags=None): if tags is not None: start_tag = '<%s %s>' % (kind, tags) else: start_tag = '<%s>' % kind self.write( '%s%s</%s>' % (start_tag, com.pprint_thing(s), kind), indent)
def _convert_to_array(self, values, name=None, other=None): """converts values to ndarray""" from pandas.tseries.timedeltas import to_timedelta coerce = True if not is_list_like(values): values = np.array([values]) inferred_type = lib.infer_dtype(values) if inferred_type in ('datetime64', 'datetime', 'date', 'time'): # if we have a other of timedelta, but use pd.NaT here we # we are in the wrong path if (other is not None and other.dtype == 'timedelta64[ns]' and all(isnull(v) for v in values)): values = np.empty(values.shape, dtype=other.dtype) values[:] = tslib.iNaT # a datelike elif isinstance(values, pd.DatetimeIndex): values = values.to_series() elif not (isinstance(values, (np.ndarray, pd.Series)) and com.is_datetime64_dtype(values)): values = tslib.array_to_datetime(values) elif inferred_type in ('timedelta', 'timedelta64'): # have a timedelta, convert to to ns here values = to_timedelta(values, coerce=coerce) elif inferred_type == 'integer': # py3 compat where dtype is 'm' but is an integer if values.dtype.kind == 'm': values = values.astype('timedelta64[ns]') elif isinstance(values, pd.PeriodIndex): values = values.to_timestamp().to_series() elif name not in ('__truediv__', '__div__', '__mul__'): raise TypeError("incompatible type for a datetime/timedelta " "operation [{0}]".format(name)) elif isinstance(values[0], pd.DateOffset): # handle DateOffsets os = np.array([getattr(v, 'delta', None) for v in values]) mask = isnull(os) if mask.any(): raise TypeError( "cannot use a non-absolute DateOffset in " "datetime/timedelta operations [{0}]".format(', '.join( [com.pprint_thing(v) for v in values[mask]]))) values = to_timedelta(os, coerce=coerce) elif inferred_type == 'floating': # all nan, so ok, use the other dtype (e.g. timedelta or datetime) if isnull(values).all(): values = np.empty(values.shape, dtype=other.dtype) values[:] = tslib.iNaT else: raise TypeError( 'incompatible type [{0}] for a datetime/timedelta ' 'operation'.format(np.array(values).dtype)) else: raise TypeError("incompatible type [{0}] for a datetime/timedelta" " operation".format(np.array(values).dtype)) return values
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): %s") % com.pprint_thing(bad_keys))
def _replot_ax(ax, freq, kwargs): data = getattr(ax, '_plot_data', None) # clear current axes and data ax._plot_data = [] ax.clear() _decorate_axes(ax, freq, kwargs) lines = [] labels = [] if data is not None: for series, plotf, kwds in data: series = series.copy() idx = series.index.asfreq(freq, how='S') series.index = idx ax._plot_data.append((series, plotf, kwds)) # for tsplot if isinstance(plotf, compat.string_types): from pandas.tools.plotting import _plot_klass plotf = _plot_klass[plotf]._plot lines.append( plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0]) labels.append(com.pprint_thing(series.name)) return lines, labels
def __unicode__(self): return com.pprint_thing( 'locals: {0}\nglobals: {0}\nresolvers: ' '{0}\ntarget: {0}'.format(list(self.locals.keys()), list(self.globals.keys()), list(self.resolver_keys), self.target))
def to_string(self, force_unicode=False): """ Render a DataFrame to a console-friendly tabular output. """ frame = self.frame if len(frame.columns) == 0 or len(frame.index) == 0: info_line = (u'Empty %s\nColumns: %s\nIndex: %s' % (type(self.frame).__name__, com.pprint_thing(frame.columns), com.pprint_thing(frame.index))) text = info_line else: strcols = self._to_str_columns(force_unicode) text = adjoin(1, *strcols) self.buf.writelines(text)
def __unicode__(self): # don't want to print out all of the items here name = com.pprint_thing(self.__class__.__name__) if self._is_single_block: result = '%s: %s dtype: %s' % ( name, len(self), self.dtype) else: shape = ' x '.join([com.pprint_thing(s) for s in self.shape]) result = '%s: %s, %s, dtype: %s' % ( name, com.pprint_thing(self.mgr_locs.indexer), shape, self.dtype) return result
def __repr__(self): output = com.pprint_thing(self.__class__) + '\n' output += 'freq: %s\n' % self.freq n = len(self) if n: output += '[%s, ..., %s]\n' % (self[0], self[-1]) output += 'length: %d' % n return output
def __repr__(self): output = com.pprint_thing(self.__class__) + "\n" output += "freq: %s\n" % self.freq n = len(self) if n: output += "[%s, ..., %s]\n" % (self[0], self[-1]) output += "length: %d" % n return output
def __unicode__(self): """ Return a string representation for this object. Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. """ prepr = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'),quote_strings=True) return '%s(%s, dtype=%s)' % (type(self).__name__, prepr, self.dtype)
def __unicode__(self): """ Return a string representation for this object. Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3. """ prepr = com.pprint_thing(self, escape_chars=("\t", "\r", "\n"), quote_strings=True) return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype)
def _convert_to_array(self, values, name=None, other=None): """converts values to ndarray""" from pandas.tseries.timedeltas import _possibly_cast_to_timedelta coerce = "compat" if pd._np_version_under1p7 else True if not is_list_like(values): values = np.array([values]) inferred_type = lib.infer_dtype(values) if inferred_type in ("datetime64", "datetime", "date", "time"): # if we have a other of timedelta, but use pd.NaT here we # we are in the wrong path if other is not None and other.dtype == "timedelta64[ns]" and all(isnull(v) for v in values): values = np.empty(values.shape, dtype=other.dtype) values[:] = tslib.iNaT # a datetlike elif not (isinstance(values, (pa.Array, pd.Series)) and com.is_datetime64_dtype(values)): values = tslib.array_to_datetime(values) elif isinstance(values, pd.DatetimeIndex): values = values.to_series() elif inferred_type in ("timedelta", "timedelta64"): # have a timedelta, convert to to ns here values = _possibly_cast_to_timedelta(values, coerce=coerce) elif inferred_type == "integer": # py3 compat where dtype is 'm' but is an integer if values.dtype.kind == "m": values = values.astype("timedelta64[ns]") elif isinstance(values, pd.PeriodIndex): values = values.to_timestamp().to_series() elif name not in ("__truediv__", "__div__", "__mul__"): raise TypeError("incompatible type for a datetime/timedelta " "operation [{0}]".format(name)) elif isinstance(values[0], pd.DateOffset): # handle DateOffsets os = pa.array([getattr(v, "delta", None) for v in values]) mask = isnull(os) if mask.any(): raise TypeError( "cannot use a non-absolute DateOffset in " "datetime/timedelta operations [{0}]".format(", ".join([com.pprint_thing(v) for v in values[mask]])) ) values = _possibly_cast_to_timedelta(os, coerce=coerce) elif inferred_type == "floating": # all nan, so ok, use the other dtype (e.g. timedelta or datetime) if isnull(values).all(): values = np.empty(values.shape, dtype=other.dtype) values[:] = tslib.iNaT else: raise TypeError( "incompatible type [{0}] for a datetime/timedelta " "operation".format(pa.array(values).dtype) ) else: raise TypeError( "incompatible type [{0}] for a datetime/timedelta" " operation".format(pa.array(values).dtype) ) return values
def _write_cell(self, s, kind='td', indent=0, tags=None): if tags is not None: start_tag = '<%s %s>' % (kind, tags) else: start_tag = '<%s>' % kind esc = {'<': r'<', '>': r'>'} rs = com.pprint_thing(s, escape_chars=esc) self.write('%s%s</%s>' % (start_tag, rs, kind), indent)
def _write_cell(self, s, kind='td', indent=0, tags=None): if tags is not None: start_tag = '<%s %s>' % (kind, tags) else: start_tag = '<%s>' % kind esc = {'<' : r'<', '>' : r'>'} rs = com.pprint_thing(s, escape_chars=esc) self.write( '%s%s</%s>' % (start_tag, rs, kind), indent)
def __unicode__(self): temp = 'Categorical: %s\n%s\n%s' values = com.pprint_thing(np.asarray(self)) levheader = 'Levels (%d): ' % len(self.levels) levstring = np.array_repr(self.levels, max_line_width=60) indent = ' ' * (levstring.find('[') + len(levheader) + 1) lines = levstring.split('\n') levstring = '\n'.join([lines[0]] + [indent + x.lstrip() for x in lines[1:]]) name = '' if self.name is None else self.name return temp % (name, values, levheader + levstring)
def summary(self, name=None): 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' % (com.pprint_thing(name), len(self), index_summary) if self.freq: result += '\nFreq: %s' % self.freqstr return result
def _replot_ax(ax, freq, kwargs): data = getattr(ax, '_plot_data', None) ax._plot_data = [] ax.clear() _decorate_axes(ax, freq, kwargs) lines = [] labels = [] if data is not None: for series, plotf, kwds in data: series = series.copy() idx = series.index.asfreq(freq, how='S') series.index = idx ax._plot_data.append(series) lines.append(plotf(ax, series.index, series.values, **kwds)[0]) labels.append(com.pprint_thing(series.name)) return lines, labels
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 reencode 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)
def _replot_ax(ax, freq, kwargs): data = getattr(ax, '_plot_data', None) ax._plot_data = [] ax.clear() _decorate_axes(ax, freq, kwargs) lines = [] labels = [] if data is not None: for series, plotf, kwds in data: series = series.copy() idx = series.index.asfreq(freq, how='S') series.index = idx ax._plot_data.append(series) lines.append(plotf(ax, series.index._mpl_repr(), series.values, **kwds)[0]) labels.append(com.pprint_thing(series.name)) return lines, labels
def _get_footer(self): footer = u'' if self.name: if getattr(self.series.index, 'freq', None): footer += 'Freq: %s' % self.series.index.freqstr if footer and self.series.name is not None: footer += ', ' series_name = com.pprint_thing(self.series.name) footer += ("Name: %s" % series_name) if self.series.name is not None else "" if self.length: if footer: footer += ', ' footer += 'Length: %d' % len(self.series) return unicode(footer)
def summary(self, name=None): """ return a summarized representation """ 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' % (com.pprint_thing(name), len(self), index_summary) if self.freq: result += '\nFreq: %s' % self.freqstr return result
def _convert_to_array(self, values, name=None): """converts values to ndarray""" from pandas.tseries.timedeltas import _possibly_cast_to_timedelta coerce = 'compat' if pd._np_version_under1p7 else True if not is_list_like(values): values = np.array([values]) inferred_type = lib.infer_dtype(values) if inferred_type in ('datetime64', 'datetime', 'date', 'time'): # a datetlike if not (isinstance(values, (pa.Array, pd.Series)) and com.is_datetime64_dtype(values)): values = tslib.array_to_datetime(values) elif isinstance(values, pd.DatetimeIndex): values = values.to_series() elif inferred_type in ('timedelta', 'timedelta64'): # have a timedelta, convert to to ns here values = _possibly_cast_to_timedelta(values, coerce=coerce) elif inferred_type == 'integer': # py3 compat where dtype is 'm' but is an integer if values.dtype.kind == 'm': values = values.astype('timedelta64[ns]') elif isinstance(values, pd.PeriodIndex): values = values.to_timestamp().to_series() elif name not in ('__truediv__', '__div__', '__mul__'): raise TypeError("incompatible type for a datetime/timedelta " "operation [{0}]".format(name)) elif isinstance(values[0], pd.DateOffset): # handle DateOffsets os = pa.array([getattr(v, 'delta', None) for v in values]) mask = isnull(os) if mask.any(): raise TypeError( "cannot use a non-absolute DateOffset in " "datetime/timedelta operations [{0}]".format(','.join( [com.pprint_thing(v) for v in values[mask]]))) values = _possibly_cast_to_timedelta(os, coerce=coerce) else: raise TypeError( "incompatible type [{0}] for a datetime/timedelta operation". format(pa.array(values).dtype)) return values
def _format_strings(self): if self.float_format is None: float_format = get_option("display.float_format") if float_format is None: fmt_str = '%% .%dg' % get_option("display.precision") float_format = lambda x: fmt_str % x else: float_format = self.float_format formatter = (lambda x: com.pprint_thing(x,escape_chars=('\t','\r','\n'))) \ if self.formatter is None else self.formatter def _format(x): if self.na_rep is not None and lib.checknull(x): if x is None: return 'None' return self.na_rep else: # object dtype return '%s' % formatter(x) vals = self.values is_float = lib.map_infer(vals, com.is_float) & notnull(vals) leading_space = is_float.any() fmt_values = [] for i, v in enumerate(vals): if not is_float[i] and leading_space: fmt_values.append(' %s' % _format(v)) elif is_float[i]: fmt_values.append(float_format(v)) else: fmt_values.append(' %s' % _format(v)) return fmt_values
def __unicode__(self): return com.pprint_thing(self.terms)
def __unicode__(self): return com.pprint_thing("locals: {0}\nglobals: {0}\nresolvers: " "{0}\ntarget: {0}".format( list(self.locals.keys()), list(self.globals.keys()), list(self.resolver_keys), self.target))
def _print_as_set(s): return '{%s}' % ', '.join([com.pprint_thing(el) for el in s])